0
string str = "0.000 0.005 0.001";
istringstream s(str);
string sub;
while (s)
{
    s >> sub;
    cout << sub << endl;
}

That is my code, I just want to output every number in str, but I get the last number twice. I know there are many better ways to implement it, but I want to know what is wrong with this code.Do I get something wrong on operator>>?

vsoftco
  • 55,410
  • 12
  • 139
  • 252
何向旋
  • 5
  • 3
  • That code does not output every number twice, it only outputs the *last* number twice. – Adam Nov 25 '15 at 05:47

1 Answers1

2

Use

while (s >> sub)
{
    cout << sub << endl;
}

instead. In your code you end up "eating" the end of stream, so s >> sub fails, and sub remains unchanged with the last good read (i.e. last number), therefore you end up displaying it twice.

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

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252