Es gibt so ein Programm:
#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;
}
Wenn ich eine gro?e Zahl (z. B. 99999999999, tats?chlich werden nur >4 Bytes ben?tigt) oder Buchstaben direkt eingebe, wird die folgende Ausgabe erzeugt:
a = 2147483647
b = 0
c = 0
d = 0
e = 4197408
f = 0
Wie ist das zu verstehen?
C++-Neulinge knien nieder und fragen den Meister um Rat
因為你輸入了超過類型長度的數(shù)據(jù),cin變成了fail狀態(tài),以后的輸入操作都不會進行。
你又沒有初始化那些變量,所以都是隨機值。
這時cin.fail()會為真。需要cin.clear()才能繼續(xù)輸入。
你用的是 Visual Studio?
你輸入的極大數(shù)或字母超出了 int 類型的范圍,導致了未定義行為。
VS 2015 中 C++ int 類型的范圍是 -2147483648~2147483647。
發(fā)生溢出時如何處理取決于編譯器。