Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is output 4196208 when input is string in an integer variable?

Tags:

c++

string

#include <iostream>
using namespace std;
int main()
{
    int x, y;
    cin >> x >> y;
    int z = x + y;
    cout << x << " " << y << " " << z;
}

Input is k m. Output is 0 4196208 4196208.

like image 465
SS613 Avatar asked Apr 15 '26 11:04

SS613


2 Answers

It is giving you these values because you have defined x and y as an integer, but you are giving them characters when it asks for input. It's not a valid operation. It will just simply give an error in form of some random number.

like image 61
cgDude Avatar answered Apr 18 '26 00:04

cgDude


Since x and y are not initialized, and std::cin>> x >> y; has failed because it expects an int and got a char, the behavior is undefined. It highly depends on the compiler. Your code on other compilers may give 0 0 0 as an output since the compiler has initialized x and y for you. On other compilers may give different value other than 4196208

Try this code,

#include <iostream>
using namespace std;
int main()
{
    int x=2,y=2;
    cin>>x>>y;
    int z=x+y;
    cout<<x<<" "<<y<<" "<<z;
    return 0;
}

The output gonna be 2 2 4. Because x and y are initialized and the exception thrown by std::cin will be ignored and the execution will continue to evaluate the sum.

Note that std::cin is an std::basic_istream object. The >> operator is overloaded to return a reference to the stream itself that could be evaluated as a boolean. So you could write some code like this

if(!(std::cin>>x>>y)) {
    //do something
}
like image 20
Moe Avatar answered Apr 18 '26 02:04

Moe