0

I'm working with string streams for homework task (translating English to 'Piglatin') and have noticed what I think is different behaviour from normal streams, which I don't understand.

The following syntax is what I was taught was 'foolproof' to use for regular streams. But with string streams I sometimes lose the final word in line:

stringstream ss(line);
string word;
ss >> word;
while(!ss.eof())
{
  translateWord(word, translated);
  cout << translated;
  if(ss.peek() == ' ')
    cout << ' ';
  ss >> word;
}

line = but fruit flies like a banana! Expected output: utbay uitfray iesflay ikelay away ananabay! Actual output: utbay uitfray iesflay ikelay away

However, with the following version (not what I've been taught) the final word isn't lost:

getline(input, line);
stringstream ss(line);
string word;
while(!ss.eof())
   {
      ss >> word;
      translateWord(word, translated);
      output << translated;
      if(ss.peek() == ' ')
         output << ' ';
   }

line = but fruit flies like a banana! Expected output: utbay uitfray iesflay ikelay away ananabay! Actual output: utbay uitfray iesflay ikelay away ananabay!

It seems to be to do with the placement of ss >> word .

Can anyone explain this difference? And why string stream behaviour seems to be different from regular streams.

Thanks in advance and sorry if I've missed anything obvious!

Ben123
  • 137
  • 6
  • 1
    Does this answer your question? [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Botje Jan 03 '20 at 12:25
  • The difference in behavior is very probably because you provided an extra newline to the `cin` version. `>>` stops reading when it encounters whitespace. – Botje Jan 03 '20 at 12:26
  • The "canonical" almost foolproof loop is `while (ss >> word)`. – molbdnilo Jan 03 '20 at 13:45

0 Answers0