简体   繁体   中英

Using cin.get(); Twice

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM