mr.loop
mr.loop

Reputation: 1005

Behavior of std::cin on failure

New to C++ and I was checking the behavior of cin on unexpected inputs and wrote the following code

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main() {
    
    int num = -1;

    cin >> num;
    cout << num << "\n";

    char alph = 'z';

    cin >> alph;
    cout << alph << "\n";

    return 0;
}

So, its supposed to take a number and then a character. Here are the results on different types of inputs

5 a
5
a
5a
5
a
aa
0
z

First one is expected.

In second one, I read here that since std::cin is able to extract 5 the operation will be successful leaving a in the buffer. So, that a is taken by our character input.

I am not able to understand the third case. Here the first cin extraction fails.

Then what happens? Because the second cin doesn't do anything. Are none of the a's being left in the buffer.

Upvotes: 0

Views: 775

Answers (1)

paulsm4
paulsm4

Reputation: 121649

The very link you cited explains what's happening:

https://www.learncpp.com/cpp-tutorial/stdcin-and-handling-invalid-input/

When the user enters input in response to an extraction operation, that data is placed in a buffer inside of std::cin.

When the extraction operator is used, the following procedure happens:

  • 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 (this is the case most of the time). 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.

So far, so good. The article continues:

[Upon an input error] 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 32767.

Additional inputs are skipped, leaving y with the initialized value of 0.

This explains the "0" you're seeing. It also explains why "z" wasn't replaced with "a".

Upvotes: 1

Related Questions