Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cin.get(); Twice

Tags:

c++

I don't understand why it might be needed twice, this is a quote from the book I am reading;

The cin.get() statement reads the next keystroke, so this statement causes the program to wait until you press the Enter key. (No keystrokes get sent to a program until you press Enter, so there’s no point in pressing another key.) The second statement is needed if the program otherwise leaves an unprocessed keystroke after its regular input. For example, if you enter a number, you type the number and then press Enter.The program reads the number but leaves the Enter keystroke unprocessed, and it is then read by the first cin.get().

I place it in the source code and don't see the point of it being there twice.

You type in some numbers and press enter it ends the program, only different is you press enter twice if nothing is entered before ending.

The point of it is to pause the program, and it does that so why the use of it twice?

like image 637
Ayfiaru Avatar asked Jan 16 '23 15:01

Ayfiaru


1 Answers

cin.get(); retrieves a single character from the input. So if you have 5\n (\n being equivalent to pressing ENTER) on the input, cin.get(); will return 5, and another cin.get(); will return \n. If you are reading multiple numbers one after another, say in a while loop, if you forget about the \n character, you are likely going to run into issues.

Using cin.ignore(256, '\n'); can also correct this issue once you are done reading the characters you want or care about.

like image 99
Drise Avatar answered Jan 25 '23 23:01

Drise