C++ read integers from file and save into array

一世执手 提交于 2020-12-26 20:19:22

问题


I'm making a program that reads only integers from text file. I want to make a function that reads integers and stores them in an array so I can use that array later to sort them with bubble sort. This is what I have so far but the output I get is some random -803234.... number :

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            cout << "numbers: " << A[i] << endl;
        }
        file.close();
    }
    cout << "numbers in array: " << A[numbers] << endl;
}

回答1:


You don't store the numbers in the array at any point:

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            // you're printing A[i] but you haven't stored
            // anything there.
            cout << "numbers: " << A[i] << endl;

I assume that numbers is the number of entries in the file and that you intended to read the values the same way you read numbers but into A[i].

cin >> A[i];

The last part of your code also tries to print beyond the last entry of the array:

cout << "numbers in array: " << A[numbers] << endl;

Remember, C++ arrays are 0 based, so A[numbers] is the *numbers + 1*th entry.




回答2:


std::vector<int> read_ints(std::istream& is)
{
    std::vector<int> result;
    std::copy(std::istream_iterator<int>(is),
              std::istream_iterator<int>(),
              std::back_inserter(result));
    return result;
}

If you can't use vectors, you've got a problem because you now need to check for end of file and for running out of space in your array...

this function will check for both, and return the number of integers that have been placed into the buffer:

template<size_t N>
size_t read_ints(int (&dest)[N], std::istream& is)
{
    size_t i = 0;
    while (i < N && is >> dest[i]) {
        ++i;
    }
    return i;
}

non-template version:

#define BUFFER_LEN 100

size_t read_ints(int (&dest)[BUFFER_LEN], std::istream& is)
{
    size_t i = 0;
    while (i < BUFFER_LEN && is >> dest[i]) {
        ++i;
    }
    return i;
}


来源:https://stackoverflow.com/questions/35900988/c-read-integers-from-file-and-save-into-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!