3

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.

Ahsan Tarique
  • 581
  • 1
  • 11
  • 22

1 Answers1

2

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770