这是什么错误?a比较小就不会报错

img

img

如果你输入的数值太大超出了int的数值范围或格式不合法,执行cin >> ar[a];后输入流的failbit被置1,在这以后每次执行cin.peek()返回的是eof,每次执行cin>>ar[a];都直接返回(因为failbit被置1),因此循环就变成死循环,a的值不断增大,以至于越界访问ar数组,直到访问冲突程序终止。

正确的写法是每次读入数据后都应该判断cin的状态是否是在good状态

while (cin >> ar[a])
  a++;

这个循环的结束条件是遇到输入流结尾(EOF),如果你是在终端输入的话,Windows按ctrl+z,Linux按ctrl+d,再回车,表示输入流结束。

以下是参考信息

FROM https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt

If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set. For signed integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() (respectively) is written and failbit flag is set. For unsigned integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits::max() is written and failbit flag is set.

FROM https://en.cppreference.com/w/cpp/io/basic_istream/peek

If good() == true, peek() returns the next character as obtained by rdbuf()->sgetc(). Otherwise, peek() returns Traits::eof().

a比较小就不会保存?不是ar吗?

a太大了就数组越界了

数组ar的下标范围是0到999,a的值超过999的话,就越界了