c++ - stringstream odd behavior after string with one word -
this question has answer here:
- how clear stringstream? [duplicate] 1 answer
i have code example:
#include <iostream> #include <sstream>  using namespace std; int main(){     stringstream ss;     string buffer,first_word;     int i;     for(i = 0; < 4; i++){         getline(cin,buffer);    // getting line         ss.str(buffer);         // initializing stream         ss>>first_word;         cout<<first_word<<endl;         ss.str(string());       // cleaning stream     }     return 0; } with input:
line 1 spaces line 2 spaces alone line 4 spaces the output expect first words of lines, this:
line line alone line but getting this:
line line alone alone so, stringstream not updating after getting line has 1 word.
please explain me, don't want right answer code, want know why.
thank you.
if bothered check state of stream, see 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 problem.
Comments
Post a Comment