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.

3
  • 2
    Is this answer of any help? Commented May 1, 2019 at 11:37
  • 2
    ss << line; adds to the string stream. Commented May 1, 2019 at 11:41
  • 2
    And the clear function doesn't do what you might think it does. Commented May 1, 2019 at 11:51

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.