Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra character from StringStream to String in C++ [duplicate]

I was writing a code in C++ 11 that would read some lines and print the first word of each line. I decided to use getline and stringstream.

string line, word;

stringstream ss;

while(somecondition){
    getline(cin, line);
    ss << line;
    ss >> word;

    cout << word << endl;
}

I tried testing this piece of code with the following input:

a x
b y
c z

The expected output would be:

a
b
c

But the actual output is:

a
xb
yc

Could someone please explain why this is happening?

Things I have tried:

  1. ss.clear(); inside the while loop

  2. initializing the strings to empty inside the while loop: word = "";

Nothing seems to work, and all produce the same output.

  1. However, when I declared the stringstream ss; inside the while loop, it worked perfectly.

I would be very glad if someone could explain why putting the stringstream declaration outside the while loop may cause the occurance of extra character.

Also I used g++ compiler with --std=c++11.

like image 886
Ahsan Tarique Avatar asked Feb 01 '26 13:02

Ahsan Tarique


1 Answers

ss.clear() does not clear the existing content of the stream, like you are expecting. It resets the stream's error state instead. You need to use the str() method to replace the existing content:

while (getline(cin, line)) {
    ss.str(line);
    ss.clear();
    ss >> word;
    cout << word << endl;
}

Otherwise, simply create a new stream on each iteration:

while (getline(cin, line)) {
    istringstream iss(line);
    iss >> word;
    cout << word << endl;
}
like image 104
Remy Lebeau Avatar answered Feb 04 '26 01:02

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!