Questions about C++ input
漂亮男人
漂亮男人 2017-07-03 11:42:01
0
2
905

There is such a program:

#include <iostream>

using namespace std;

int main()
{
    int a, b, c, d, e, f;
    cin >> a;
    cout << endl << "a = " << a << endl << endl;
    cin >> b;
    cout << endl << "b = " << b << endl << endl;
    cin >> c;
    cout << endl << "c = " << c << endl << endl;
    cin >> d;
    cout << endl << "d = " << d << endl << endl;
    cin >> e;
    cout << endl << "e = " << e << endl << endl;
    cin >> f;
    cout << endl << "f = " << f << endl << endl;
    return 0;
}

If I directly input a large number (such as 99999999999, in fact, only >4 bytes are enough), or letters, the following output will be produced:

a = 2147483647


b = 0


c = 0


d = 0


e = 4197408


f = 0

How to understand this?

C Novices kneel down and ask the master for advice

漂亮男人
漂亮男人

reply all(2)
巴扎黑

Because you entered data that exceeds the type length, cin becomes a fail state, and future input operations will not be performed.
You didn’t initialize those variables, so they are all random values.
At this time, cin.fail() will be true. cin.clear() is required to continue typing.

淡淡烟草味

Are you using Visual Studio?

The extremely large number or letter you entered exceeds the range of the int type, resulting in undefined behavior.

The range of C++ int type in VS 2015 is -2147483648~2147483647.

How to handle overflow when it occurs depends on the compiler.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template