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

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.

Leave a Comment