0

I have this code for example:

#include <iostream>
#include <sstream>

using namespace std;
int main(){
    stringstream ss;
    string buffer,first_word;
    int i;
    for(i = 0; i < 4; i++){
        getline(cin,buffer);    // getting line
        ss.str(buffer);         // initializing the stream
        ss>>first_word;
        cout<<first_word<<endl;
        ss.str(string());       // cleaning stream
    }
    return 0;
}

with this input:

line one with spaces
line two with spaces
alone
line four with spaces

The output I expect is just the first words of the lines, like this:

line
line
alone
line

But I am getting this:

line
line
alone
alone

So, stringstream is not updating after getting a line that only has one word.

Please explain this to me, I don't want the right answer with code, I want to know why.

Thank you.

eLRuLL
  • 18,488
  • 9
  • 73
  • 99
  • The SS has already encountered eof so you need to reset the flag before reusing it. Check this out http://stackoverflow.com/questions/2848087/how-to-clear-stringstream – Carth May 19 '13 at 05:24

1 Answers1

1

If you bothered to check the state of the stream, you will see this line:

    ss>>first_word;
    if (!ss.good()) std::cout << "problem." << std::endl;
    cout<<first_word<<endl;

Does indeed output "problem."

    ss.str("");
    ss.clear();

Fixes the problem.