0

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;
}
Community
  • 1
  • 1
pratZ
  • 3,078
  • 2
  • 20
  • 29
  • 1
    lots of possible duplicates http://stackoverflow.com/questions/2184125/getting-input-from-user-using-cin?rq=1 http://stackoverflow.com/questions/2735315/c-cin-whitespace-question?rq=1 – nurettin Aug 11 '12 at 09:53

3 Answers3

3

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

Because you're using it in a loop. So each time around cin eats 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 fact s contains none.

A simple way to test this would be to print:

cout << s << "$";

However the most interesting characteristic of the code is how the while tests the istream returned by << which in a boolean context yields exactly what you want: whether the input is done or not.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

Using the input operator on a stream by default stops at whitespace, and skip leading whitespace. So since you reading in a loop, it skips whitespace while reading all "words" you input, and then print it inside the loop with a trailing newline.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You probably ignored the fact that whenever you are entering a new string ( after a white space character i.e. a newline, tab or blank-space ) it is being re-assigned to string s in the while loop condition. To verify this you can simply do something like :

int i=1;
while (cin >> s)
cout << i++ << ": " << s << endl;

instead of :

while (cin >> s)
cout << s << endl;

Run this and everything would be crystal clear :)

cirronimbo
  • 909
  • 9
  • 19