'when I input string instead of integer then why it does print 0 and 1 on VScode?

when I input string instead of integer then why it does print 0 and 1 on VScode?

#include <iostream>
using namespace std;

int main()
{
    int a , b ;
    cout<<"give the value of a and b : ";
    cin>>a>>b;
    cout<<"a :"<<a<<"b : "<<b;

    return 0;

}

Could you please tell me, does these 0 and 1 are the default input or they are just a garbage ?



Solution 1:[1]

This is because when the extraction fails zero is written to the value, as quoted in the statement below:

If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set. For signed integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() (respectively) is written and failbit flag is set. For unsigned integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() is written and failbit flag is set.

Thus, when the first extraction std::cin >> a fails, failbit is set and additionally a is set to value 0. That is why you get 0 for the first output.

But note that since the failbit was set in the first extraction, b do not get any value i.e. it has indeterminate value and using that value(which you do in std::cout<<b) is undefined behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1