DEV Community

Mo'men Ahmed
Mo'men Ahmed

Posted on

How std::cin works in C++?

std::cin is used to get user input from external source.

When the user enters input, that data is put in a buffer inside of std::cin. The buffer is used to hold user input while it’s waiting to be extracted to variables.

std::cin extraction steps:

  • If there is data already in the input buffer, that data is used for extraction.

  • If the input buffer contains no data, the user is asked to input data for extraction. When the user hits enter, a ‘\n’ character will be placed in the input buffer.

  • operator>> extracts as much data from the input buffer as it can into the variable (ignoring any leading whitespace characters, such as spaces, tabs, or ‘\n’).

  • Any data that can not be extracted is left in the input buffer for the next extraction.

Extraction succeeds if at least one character is extracted from the input buffer. Any unextracted input is left in the input buffer for future extractions. For example:

int x {0};
std::cin >> x;
Enter fullscreen mode Exit fullscreen mode

If the user enters: "22m", the variable x is filled with "22" leaving the "m" alone in the buffer.
Extraction fails if the input data does not match the type of the variable being extracted.
For example, if the user enters "m" extraction would fail because "m" can not be extracted to an integer variable. But then what would be the value of x?
Before c++ 11:a failed extraction would not modify the variable being extracted to.
However, as of C++11, a failed extraction due to invalid input will cause the variable to be zero-initialized.

Look at this code

// uint16_t is a typedef for unsigned short
std::uint16_t x {0}; // max is UINT16_MAX (65535)
std::cin >> x;
Enter fullscreen mode Exit fullscreen mode

when a user enters 65537, std::cin goes immediately into failure mode, but also assigns the closest in-range value to the variable. Consequently, x is left with the assigned value of 65535. Additional inputs are skipped.

Before C++11, a failed extraction would not modify the variable being extracted.
However, as of C++11, an out-of-range failed extraction will cause the variable to be set to the closest in-range value.

Also note that when std::cin goes to failure mode, it will skip any other extractions, so you should put it back to the normal mode:

if (std::cin.fail())
{
    std::cin.clear();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
quangvinh24304 profile image
Quang Vinh

if I cin >> x , then the consolo screen appears wanting me to enter the value of x, but I just press Enter continuously so then does cin stop the input command