How does the compiler deal with the inputs following an invalid input exactly?

I know that, roughly speaking, when the user enters an invalid input, 0 will be assigned to that input (the failbit flag is set on the input stream) and all the subsequent inputs becomes unreliable.

In such cases, I wonder if some unreliable value (or some value with special meaning like 0 above) will be assigned to those subsequent inputs? Or if those those subsequent inputs will simply be escaped?

I actually made a toy program with multiple std::cin >> variables; statements to see if any value would be assigned to variables after the failbit flag has been set.

enter image description here

It seems that, on my computer, all those subsequent cin are being escaped and the variables that would have been assigned a value by those subsequent cin remain to have the original values which were assigned to them during their initialisations (a is 0 while b and c are still 100 and 1000 respectively).

May I ask if such escapes happens all the time? Or if such behaviour differs from machine to machine?

Also, may I ask if the invalid input remain in the input buffer after the failbit flag is set unless we clear the input buffer?

Thanks in advanced!

1 answer

  • answered 2021-06-23 12:34 Caleth

    The various std::istream& operator>>(std::istream& is, arithmetic & num) are functions that an implementation (not just "the compiler") must provide. The standard defines what they do.

    The steps are laid out in the definition of FormattedInputFunction and std::num_get::get. Specifically:

    If the sentry returned false or sentry's constructor threw an exception, no input takes place

    If the conversion function fails to convert the entire field, the value ​0​ is stored in v.

    So the first input failure writes 0 to a number, and subsequent calls don't modify the right hand side argument.