Question

Consider this code:

int a;
cin >> a;

The input doesn't stop when you enter for example 1 or 2; it waits until you press ENTER. How does this work? Why does cin wait for your input until you press ENTER?

Was it helpful?

Solution 2

cin just has a buffer behind it that gets filled up with input and then gets emptied as you use the extraction operator (>>). When and how it gets filled up depends on the platform. In Unix-like systems, for example, the input terminal is in either canonical or non-canonical mode. In canonical mode, input is made available line by line. In non-canonical mode, it is available immediately. It's possible to change between these modes (check man termios).

The actual size of the standard input buffer is implementation-defined.

OTHER TIPS

Your runtime environment and your terminal control the raw keyboard input. Typically, they only send the input to the application line by line, to allow for editing. You have to speak to your terminal, in a platform-dependent way, if you want it to send you the keyboard input immediately.

(This is often referred to as "raw" mode, as opposed to the usual, line-buffered "cooked" mode. Note that the cooked mode also handles backspace and delete and cursor movement and all that.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top