Why does the cin command leave "\ n" in the buffer?

This is due to: cin and getline skip input But they do not answer why this is happening, only how to fix it.

Why does cin leave "\ n" in the buffer, but only cin.getline accepts it?

eg:

 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 doesn't this happen with cin , but does it happen with cin.getline ?

+6
source share
2 answers

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

When you say cin >> something , you want to get exactly something , nothing more. The final marker is not part of it, so it is not consumed. Unless you have a special type for the string, but there is no such thing in the standard library.

Despite the lack of references from the standard, this may be perceived as an opinion, but it is logical. They have different semantics . There is another difference. getline works as unformatted input , operator>> works as formatted input . I highly recommend reading these links to get the differences. This also suggests that they are semantically different.

Another answer, better or less debatable, would be to quote a standard that, I am sure, says how getline behaves, and how operator>> behaves for different types and says that it works like that because the standard says so. That would be good, because the standard absolutely defines how everything works, and it can do it arbitrarily ... And this rarely explains the motivation and logic of the design.

+8
source

You are not comparing cin with cin.getline , but rather cin.operator>> and cin.getline , and that is exactly what these functions are defined. The answer to the question “why” is “by definition”. If you want a rationale, I cannot give it to you.

cin.getline reads and consumes before entering a new line \n . cin.operator>> does not use this new line. The latter performs formatted input, skipping leading spaces to the end of the object that it read (in your case, regardless of foo ) "stops" (in case foo is int , when the character is not a number). A new line is what remains when the quantity is consumed from the input line. cin.getline reads a line and consumes a new line by definition.

Be sure to always check for errors with each stream operation:

 if(cin >> foo) 

or

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

Note. I used std::getline instead of a stream member, because in this case there is no need for any magic numbers ( 100 in your code).

+4
source

Source: https://habr.com/ru/post/981442/


All Articles