为什么整数溢出导致C + + iostreams错误? [英] Why does integer overflow cause errors with C++ iostreams?
问题描述
好的,所以我有一些问题,C + + iostreams感觉很奇怪,但它可能是定义的行为,考虑到发生在MSVC ++和G ++。
Ok, so I have some problems with C++ iostreams that feels very odd, but it is probably defined behaviour, considering this happens with both MSVC++ and G++.
我有这个程序:
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
cout << a << endl;
cin >> a;
cout << a << endl;
return 0;
}
如果我故意通过给第一个cin一个大于一个int的最大限制,所有进一步调用 cin.operator>>()
会立即返回一些原因, a
设置为某个值。该值似乎未定义。
If I intentionally overflow by giving the first cin a value that is larger than the max limit of an int, all further calls to cin.operator>>()
will immediately return for some reason, and a
is set to some value. The value seems to be undefined.
为什么,这个行为记录在哪里?有没有办法弄清楚这样的溢出是否发生?
Why, and where is this behavior documented? Is there a way to figure out if such an overflow occured?
此外,这个类似的程序似乎工作,我打算。如果我溢出的值,它会给 a
一些值,继续,如果溢出从未发生。
Also, this similar program seems to work as I intend. If I overflow the value, it will give a
some value, and continue on as if the overflow never happened.
#include <cstdio>
using namespace std;
int main()
{
int a;
scanf("%d", &a);
printf("%d\n", a);
scanf("%d", &a);
printf("%d\n", a);
scanf("%d", &a);
printf("%d\n", a);
return 0;
}
推荐答案
iostreams旨在检测错误并进入错误状态。
iostreams is designed to detect errors and enter an error state. You get the same result from integer overflow as from entering a non-numeric string.
输入 cin
(或任何流)到 bool
或检查 cin.rdstate()
以确定是否发生错误。
Cast cin
(or any stream) to bool
or check cin.rdstate()
to determine if an error has occurred.
调用 cin.clear()
和 cin.ignore()
出错了。
对于官方文档,标准不幸在iostreams的肠子里有点不可思议。参见§27.6.1.2.1,27.6.1.2.2和22.2.2.1.1 / 11(不开玩笑):
As for the official documentation, the Standard unfortunately gets a bit inscrutable in the bowels of iostreams. See §27.6.1.2.1, 27.6.1.2.2, and 22.2.2.1.1/11 (no kidding):
在阶段2中累积的字符序列将导致scanf报告输入失败。 ios_base :: failbit已分配给错误。
— The sequence of chars accumulated in stage 2 would have caused scanf to report an input failure. ios_base::failbit is assigned to err.
scanf的文档是不可穿透的,我会相信,溢出应该是一个错误。
The documentation for scanf is just as impenetrable, and I'll take it on faith that overflow is supposed to be an error.
这篇关于为什么整数溢出导致C + + iostreams错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!