Using cin.get (); Twice

I do not understand why this may be needed twice, this is a quote from a book that I am reading;

The cin.get () operator reads the next keystroke, so this operator makes the program wait until you press Enter. (No keystrokes are sent to the program until you press Enter, so as not to press another key.) The second statement is necessary if the program otherwise leaves the raw keystroke after its usual input. For example, if you enter a number, enter the number and press Enter. The program reads the number, but not pressing the Enter key is not processed, and then it is read first by cin.get ().

I put it in the source code and do not see that its point was there twice.

You enter some numbers and press Enter, this ends the program, only different - you press twice if nothing was entered before the end.

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

+3
source share
1 answer

cin.get();extracts one character from input. Therefore, if the input 5\n( \nequivalent to pressing ENTER), cin.get();returns 5, and the other cin.get();returns \n. If you read several numbers one after the other, say, in a loop while, if you forget about the sign \n, you are likely to run into problems.

Using cin.ignore(256, '\n');can also fix this problem after you finish reading the characters you want or care about.

+8
source

All Articles