All, I've got some code here that I can't explain the behavior of. It is posted below. I looked at Why does integer overflow cause errors with C++ iostreams?, but it doesn't really answer my question.
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
int x;
scanf("%d", &x);
cout << "Value of x = " << x << endl;
cin >> x;
cout << "Failure Detected = " << cin.fail() << endl;
cout << "Value of x = " << x << endl;
return 0;
}
So, what I expect this code to do is read in an integer, print out the value of that integer, read in another integer (into the same variable), and print out that integer. If I enter input of 7 and 2, then it works as expected. However, if I enter 2^31 (overflow int by one) for both the first and second input, then the first output will say "Value of x = -2147483648" and the second output will say "Value of x = 2147483647". cin.fail() will also return true. What is cin doing to the input? I thought that if cin.fail() was true, the value of x should be left unaffected. If not left unaffected, I would expect the value of x to overflow as normal (like scanf does). What's going on with cin here? Why is it capping the value at integer max value?
Thanks in advance!