zbqv zbqv - 1 month ago 16
C++ Question

C++, read an array of number from a file

The following is part of my C++ code,

argv[2]
is the path to the input file.
And I found out that though I get the correct number of element (
arr_size
) in the input file, the code in while loop didn't seem to be executed. The result is that all element in
arr[]
retain its original value(0).

ifstream inFile( argv[2] );

// get the number of element
int arr_size = distance(istream_iterator<int>(inFile), istream_iterator<int>() );

int * arr = new int[arr_size];

int idx(0);
while ( inFile >> arr[idx] ) {
idx++;
}


I have tried

while ( !inFile.eof() ) {
inFile >> arr[idx];
idx++;
}


,but still get the same result.

The input file is just like below:

3 8 7 4 6 2 1 9 0 5


What's wrong with my code?

Answer

At this line

int arr_size = distance(istream_iterator<int>(inFile), istream_iterator<int>() );

the file was already read to end.

You have to reset the ifstream using seekg(0) to start reading it again.

Also use the 1st version of your while loop, and better use a std::vector<int> and push_back() instead of managing the memory yourself.