0

Why is ifstream returning the last value of strings twice?

in

size_t c;
    while (1){
        myfile >> c;
        cells.push_back(c);
        if (myfile.eof()) break;
    }
    for (int i = 0; i < cells.size(); i++) cout << cells[i] << endl;

with the input

    2   3
    9   7   11
    12  5   6
    3   4

cells[7] = cells[8] = 4

I've done this with a few similarly formatted inputs and it does this for all of them.

  • [Because youre using while!(myfile.eof())](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Borgleader Nov 13 '14 at 17:07

2 Answers2

3

The idiomatic way to do this is

while (myfile >> c){

}

This completely eliminates your problem, as the eof() is not reached when the last value is read, but when the stream fails to read, so after that fail you do another push_back. The advantage of the above while construct is that it will break immediately on fail.

Captain Giraffe
  • 13,403
  • 5
  • 35
  • 65
0

You should always check the result of an I/O operation before you use the data it returns.

In this case, that means your check on eof() should precede the push_back() call. To make the code safer you should also add a check for fail() on the stream, since the stream can fail for other reasons than reaching EOF.

Steve Townsend
  • 51,210
  • 8
  • 87
  • 134