1
string tmp("f 1/2/3 4/5/6 7/8/9");
istringstream stin(tmp);
string token;
char ch;
int a,b,c,e;
stin >> token;
while(stin){
    stin >> a >> ch >> b >> ch  >>c;
    cout <<a <<  " "<<b <<" "<<c <<  endl;
}

Why the output is 1 2 3 4 5 6 7 8 9 7 8 9 But why for changing while(stin) to while(!stin.eof()) the output is

  • 1 2 3 4 5 6 7 8 9

So what is the difference between while(stin) to while(!stin.eof()) Thanks a lot!

user3722836
  • 141
  • 10
  • 1
    the `operator bool` will return whether an error bit is set, `eof()` will only return if you have reached the end of file. – Red Alert Nov 16 '14 at 03:36

1 Answers1

3

The reason is you don't check if the read succeeded before printing out the variables. The eof() check stops the reading earlier (because it hits the end of the std::istringstream) but contains its own subtle bug:

see: Why is iostream::eof inside a loop condition considered wrong?

For example try adding a space to the end of the input: "f 1/2/3 4/5/6 7/8/9 " and you get the same, repeated, output with the eof() check.

The ideal solution might be something like this:

int main()
{
    istringstream stin("f 1/2/3 4/5/6 7/8/9");

    string token;

    char ch;
    int a, b, c;

    stin >> token;
    while(stin >> a >> ch >> b >> ch >> c) // only loop on successful read
    {
        cout << a << " " << b << " " << c << endl;
    }
}
Community
  • 1
  • 1
Galik
  • 42,526
  • 3
  • 76
  • 100