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!