Home  >  Q&A  >  body text

Questions about C++ input

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

漂亮男人漂亮男人2688 days ago856

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-07-03 11:44:01

    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.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-03 11:44:01

    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.

    reply
    0
  • Cancelreply