#include <iostream>
#include <fstream>
#include <sstream>
usingnamespace std;
int main()
{
ifstream ifs("data.txt");
istringstream ss;
string line, word;
while( getline(ifs, line) )
{
ss.str( line );
while( ss >> word )
cout << word << " ";
cout << "\n";
}
}
The problem is that only the first line of the file gets printed. From the appearance of my console window, it looks like blank lines are being printed for the remaining lines of the file. I can't figure out why. If anyone can clue me in I would be most grateful.
Thanks. I found a tutorial which seems to imply that the string stream must be cleared, or created anew, before it is re-used. This is consistent with your solutions, both of which work. Could it be that the stringstream goes into an eof() state after processing the first line, and this needs to be reset explicitly.
When re-using any stream you always need to be concerned about the prior error state, so before you re-use the stream it is best to clear any errors. And don't forget eof() is only one of the errors that may be set on a stream.
#include <iostream>
#include <fstream>
#include <sstream>
usingnamespace std;
int main()
{
ifstream ifs("data.txt");
istringstream ss;
string line, word;
while( getline(ifs, line) )
{
ss.clear();
ss.str( line );
while( ss >> word )
{
cout << word << " ";
}
cout << "\n";
}
}
but as soon as a elaborate on the code inside the inner while loop, things go awry. for example, I want to only print out the lines that contain a certain word...
In my latest failed attempt I used the search string "apple" when I should have used "apples". Nothing printed because the program could not find the word "apple". In other words the code was working fine.