zbqv zbqv - 1 year ago 98
C++ Question

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

The following is part of my C++ code,

is the path to the input file.
And I found out that though I get the correct number of element (
) in the input file, the code in while loop didn't seem to be executed. The result is that all element in
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] ) {

I have tried

while ( !inFile.eof() ) {
inFile >> arr[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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download