[英]what is stored in the input buffer if I provide double for an int in c++?
My code is : 我的代码是:
int main()
{
int x,y,z;
cout<<"Please input first integer : ";
x = getInt();
cin>>z>>y;
cout<<x <<"\n"<<z<<"\n"<<y;
return 0;
}
when I provide input such as 当我提供诸如
Please input first integer : 34.5
34
0
-2
Process returned 0 (0x0) execution time : 3.431 s
Press any key to continue.
What's happening over here?? 这是怎么回事?
When trying to read an integer (using >>
), the input 34.5
is no different from the strings 34abcd
or 34 42
. 尝试读取整数(使用
>>
)时,输入34.5
与字符串34abcd
或34 42
。
The operator>>
reads characters that could be part of an integer, 3
and 4
, and then stops (leaving the rest in the input buffer). operator>>
读取可能是整数3
和4
一部分的字符,然后停止(将其余字符保留在输入缓冲区中)。
When continuing with cin >> z
the buffer still contains .5
. 当继续
cin >> z
,缓冲区仍包含.5
。 As the .
作为
.
cannot be part of an integer, the input fails and z
is set to 0. 不能是整数的一部分,输入失败并且
z
设置为0。
After that, the stream is in a failed state and the input to y
isn't even attempted. 之后,流处于失败状态,甚至没有尝试输入
y
。 The stream state has to be cleared if we want to try more input. 如果我们想尝试更多输入,则必须清除流状态。
The result is complicated by the fact that y
is still uninitialized when the values are displayed. 由于在显示值时
y
仍未初始化的事实使结果变得复杂。 The -2
is one possible effect of this undefined behavior. -2
是此不确定行为的一种可能的影响。
If extraction fails (eg if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
如果提取失败(例如,如果在预期的数字中输入了字母),则值将保持不变,并设置故障位。
As results, subsequent calls to << are failed (failbit is set). 结果,随后对<<的调用失败(设置了失败位)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.