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:
ss.clear();
inside the while loopinitializing the strings to empty inside the while loop:
word = "";
Nothing seems to work, and all produce the same output.
- 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
.