0

using stringstream to read individual words from a sentence vs using it to parse comma separated integers behaves differently than how I expected it to.

string ok = "hello how is it going";
stringstream ss(ok);
string tmp;
while(ss)
{
    ss >> tmp;
    cout << tmp << endl;
}

i'd expect the output to be-

hello
how
is
it
going

but the output is-

hello
how
is
it
going
going

what confuses me is if I use it differently-

string ok = "10,11,12";
stringstream ss(ok);
int n;
char ch;
while(ss)
{
   ss >> n >> ch;
   cout << n << endl;
}

i get the desired output which is-

10
11
12

and not 12 being repeated as in the case with strings

JeJo
  • 30,635
  • 6
  • 49
  • 88
raultoks
  • 5
  • 3
  • 1
    Use `while(ss>>tmp)` instead of just `while(ss)` as explained in the [dupe](https://stackoverflow.com/questions/71182070/getting-last-value-printed-twice-when-reading-file-in-c) – Jason Jul 11 '22 at 12:11
  • 1
    And the difference in you second example is, that the ss will already be in fail state one iteration earlier, because of you try to read a trailing comma. – gerum Jul 11 '22 at 13:42
  • the trailing comma sets it to fail state that was the distinction i didnt get from the dupe – raultoks Jul 22 '22 at 04:23

0 Answers0