c++inputoutputcincout

Why i am getting output in cout (0 16) even i dont enter any input value in cin


#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
int b;
cin >> a >> b;
cout << a <<" "<<b;     
}
OutPut: 0 16

Your help will be apreciated Thanks in Advance! i tried by putting different input value , the results are ok , but if i dont enter any cin value the results on cout are making me confuse so i want to clear it!


Solution

  • Because it reaches the end-of-file on std::cin and it causes an internal error. Instead of throwing an exception or blocking, it goes ahead without modifying anything. What you are seeing is uninitialized garbage.

    You can see what this program does:

        #include <iostream>
        int main(){
            int a = -1;
            int b = -2;
            std::cout << std::cin.good() << std::endl;
            std::cin >> a; 
            std::cout << std::cin.good() << std::endl;
            std::cin >> b;
            std::cout << std::cin.good() << std::endl;
            std::cout << a <<" "<<b;     
        }
    

    Outputs:

    1
    0
    0
    -1 -2
    

    https://godbolt.org/z/Gbc4zj4ve

    Compare that with when you add input to cin, eg 1 2

    1
    1
    0
    1 2
    

    https://godbolt.org/z/j6e9Erqrr