#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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With