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>>
?
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?