我正在从文本文件中提取数字,并用它们填充int类型的数组。
我将这些值插入数组,同时使用这些代码行循环遍历.txt文件(其中k是.txt文件中的数字量):
for (int j = 0; j < k; j++)
inputFile >> tab[j];
当文本文件中的数字小于2,147,483,647(这是整数类型的最大大小)时,一切都会顺利进行。
当数字大于此数字时,我假设程序溢出并且无法插入,但是在此之后也无法插入任何数字。
是什么导致它在溢出发生后不再插入任何数字?
最佳答案
在 std::istream& std::istream::operator>>(std::istream&, int&)
上,cppreference表示:
Behaves as a FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, extracts an integer value by calling
std::num_get::get()
...
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value,
std::numeric_limits<T>::max()
orstd::numeric_limits<T>::min()
is written and failbit flag is set. (since c++11)
这不是规范性的,但确实提供了有关此处发生情况的不错的总结。
FormattedInputFunctions将根据流构造一个哨兵并检查其值。如果哨兵对象的评估结果为
false
,则为no input is performed。如果被操作的流among other situations设置了故障位,则该哨兵对象将评估为
false
。所以,这是怎么回事:
int
数据类型的整数。 int
设置为int
可以存储的最大可能值。 您可以通过在执行读取操作后检查故障位和整数值来检测这些溢出错误,如对Read int from istream, detect overflow问题的公认答案所述。
您可以通过使用
std::basic_ios::clear
取消故障位来从这些错误中恢复。调用clear
取消设置故障位后,进一步的读取将按照您的预期进行。
关于c++ - 当>>运算符试图输入一个大于变量可以包含的值时,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61074319/