Possible Duplicate:
C++ cin whitespace question
I’m having problem trying to understand this piece of code. I’d like to apologize if this question has already been answered but I didn’t find it anywhere. I’m a beginner and its a very basic code. The problem is >> operator stops reading when the first white space
character is encountered but why is it in this case it outputs the complete input string even if we have white spaces in our string. It outputs every word of the string in separate lines. How is it that cin>>x can take input even after the white space? Plz help me out with the functioning of this code. Thanks in advance.
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::endl;
int main()
{
string s;
while (cin >> s)
cout << s << endl;
return 0;
}
Because you’re using it in a loop. So each time around
cineats a word which you print and discards whitespace. The fact that you’re printing a newline after each word means you don’t expect to see whitespace – and in factscontains none.A simple way to test this would be to print:
However the most interesting characteristic of the code is how the
whiletests theistreamreturned by<<which in a boolean context yields exactly what you want: whether the input is done or not.