Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cin command leaves a '\n' in the buffer?

Tags:

c++

syntax

This is related to: cin and getline skipping input But they don't answer the why it happens just the how to fix it.

Why does cin leaves a '\n' in the buffer but just cin.getline takes it?

for example:

cin >> foo;
cin >> bar;//No problem
cin >> baz;//No problem.

But with cin.getline

cin >> foo;
cin.getline(bar,100);//will take the '\n'

So why it doesn't happen with cin but it does with cin.getline?

like image 337
shinzou Avatar asked Jan 23 '15 12:01

shinzou


2 Answers

Because, when you say getline you say you want to get a line... A line is string that ends with \n, the ending is integral part of it.

When you say cin >> something, you want to get precisely something, nothing more. End-line marker is not part of it, so it's not consumed. Unless you would have a special type for line, but there is no such thing in standard library.

While without citations from standard this might be taken as opinion, but this is logic behind it. They have different semantics. There is also another difference getline works as unformatted input, and operator>> works as formatted input. I strongly suggest reading of those links to get the differences. This also says that they are semantically different.

Another answer, better or not is debatable, would be to quote standard, that I am sure says, how getline behaves, and how operator>> behaves for different types, and say, it works like this, because standard says so. This would be good, because the standard absolutely defines how things work and it can do so arbitrarily... And it rarely does explain motivation and logic behind the design.

like image 150
luk32 Avatar answered Oct 25 '22 15:10

luk32


You are not comparing cin to cin.getline, but rather cin.operator>> and cin.getline, and that is exactly what these functions are defined to do. The answer to the question "why" is "by definition". If you want rationale, I can't give it to you.

cin.getline reads and consumes until a newline \n is entered. cin.operator>> does not consume this newline. The latter performs formatted input, skipping leading whitespace, until the end of the object it was reading (in your case whatever foo is) "stops" (in case foo is an int, when the character isn't a number). A newline is what remains when the number is consumed from the input line. cin.getline reads a line, and consumes the newline by definition.

Make sure to always check for error on each stream operation:

if(cin >> foo)

or

if(std::getline(cin, some_string))

Note I used std::getline instead of the stream's member because this way there's no need for any magic numbers (the 100 in your code).

like image 31
rubenvb Avatar answered Oct 25 '22 15:10

rubenvb