Edit: if you already know that the line will only have the two words, then the stringstream is unnecessary, but if you do want to use the string stream, you have to use the .str() function to set the buffer of b to line or the buffer of x to line. b.str(line); /* or */ x.str(line);
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
string filename = "prova.txt";
// ifstream in( filename ); // when used in anger
stringstream in( "wordA wordB\n" // for the purposes of demonstration
"wordC wordD\n""wordE wordF\n" );
for ( string a, b; in >> a >> b; )
{
cout << a << " " << b << '\n';
}
}
If you are determined to read whole lines before breaking them up, then keep the relevant quantities in a very local scope.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
string filename = "prova.txt";
// ifstream in( filename ); // when used in anger
stringstream in( "wordA wordB\n" // for the purposes of demonstration
"wordC wordD\n""wordE wordF\n" );
string line;
while ( getline( in, line ) )
{
string a, b;
stringstream( line ) >> a >> b;
cout << a << " " << b << '\n';
}
}
Whatever you do, don't use .eof() to test for end-of-file!