何向旋
何向旋

Reputation: 5

about istringstream and >>operator

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

Upvotes: 0

Views: 133

Answers (1)

vsoftco
vsoftco

Reputation: 56577

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?

Upvotes: 2

Related Questions