With this code snippet:
while (ss) { ... }
You are checking the state of the string stream
. If it contains valid data the loop will continue. This is why you are seeing the last word twice...
1st iteration of loop:
while ( ss ) { // checks if there is valid data in ss and for errors (true)
ss >> word; // ss inserts "hello" into word.
cout << word << endl; // cout prints "hello" to the console.
}
2nd iteration of loop:
while ( ss ) { // checks again if there is valid data (true)
ss >> word; // ss inserts "world" into word.
cout << word << endl; // cout prints "world" to the console.
}
3rd iteration of loop:
while ( ss ) { // checks again if there is valid data (true)
ss >> word; // ss already contains "world", may optimize or copy over...
cout << word << endl; // cout prints "world" to the console.
}
4th iteration of loop:
while ( ss ) { // ss encountered end of stream (false) exits loop.
ss >> word; // nothing inserted as loop has exited.
cout << word << endl; // nothing printed as loop has exited.
}
Instead of trying to use your stringstream
as a condition for a loop try using the process of extracting data from the stringstream
into a variable for your condition.
while( ss >> word ) {
cout << word << endl;
}
1st iteration of loop:
while ( ss >> word ) { // checks if ss inserted data into word
// ss inserts "hello" (true)
cout << word << endl; // cout prints "hello" to the console.
}
2nd iteration of loop:
while ( ss >> word ) { // checks again if ss inserted data into word
// ss inserts "world" into word (true)
cout << word << endl; // cout prints "world" to the console.
}
3rd iteration of loop:
while ( ss >> word ) { // checks again if ss inserted data into word
// ss fails to insert data (false) loop exits here
cout << word << endl; // nothing printed as loop exited
}