Reputation: 705
My understanding is that the operator >>
returns the left operand, so cin >> x
returns cin
which has a value of false
if we encounter an EOF
or other errors. Now my guess is that since cin
skips whitespace, characters like \n
don't get stored. What I'd like to do is something like this:
int x;
while((cin >> x) and x != '\n')
// do stuff
So that when cin
encounters a newline in the stream, it exits the input loop (as it would normally do with say, EOF
).
Upvotes: 1
Views: 706
Reputation: 110108
Using >>
operator directly won't work, because as you say it skips whitespace including newlines.
What you can do is to read a single line using std::getline
, and then you can read all input from the line with std::stringstream
.
std::string line;
if (std::getline(std::cin, line)) {
std::istringstream ss(line);
int x;
while (ss >> x) {
//....
}
}
Upvotes: 6