My cpp program is doing something strange with scoping when I use it string streams. When I place initialization of the strings and string streams in the same block as where I use it, there are no problems. But if I place it one block above, the string stream doesnt output strings properly
correct behaviour, the program prints each token separated by whitespace:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
while (true){
//SAME BLOCK
stringstream line;
string commentOrLine;
string almostToken;
getline(cin,commentOrLine);
if (!cin.good()) {
break;
}
line << commentOrLine;
do{
line >> almostToken;
cout << almostToken << " ";
} while (line);
cout << endl;
}
return 0;
}
Incorrect behavior, the program prints only the first inputline:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
//DIFFERENT BLOCK
stringstream line;
string commentOrLine;
string almostToken;
while (true){
getline(cin,commentOrLine);
if (!cin.good()) {
break;
}
line << commentOrLine;
do{
line >> almostToken;
cout << almostToken << " ";
} while (line);
cout << endl;
}
return 0;
}
Why does this happen?
When you "create and destroy" the stringstream
for each line, it also gets the fail
state reset.
You could fix that by adding line.clear();
just before you add the new content to line
.