怪异行为 [英] cin erratic behaviour
问题描述
我是C ++的新手。小代码示例如下:
int main(int argc,char * argv []){
字符ch1;
int int1;
cin>> ch1;
cin>> int1;
cout<< ch1<< ‘n’;
cout<< int1<< ‘n’;
返回0;
}
运行程序并输入以下内容:
az
我得到的输出是:
a
32767
我了解 a,但是为什么要输入32767的整数?我只是想测试一下,看看如果我没有分配给int1的数值,而是使用'z',会发生什么情况。
我尝试输入:
ax
...我也得到相同的结果。
现在,如果使用 short int1
int int1 >并输入以下内容运行程序:
az
我得到输出:
a
0
PS
sizeof(int)= 4
sizeof(short)= 2
我正在使用64位计算机。
当输入流无法读取有效数据时,它不会更改您传递的值。 z不是有效数字,因此int1保持不变。 int1尚未初始化,因此它的值为32767。读取数据后,请检查cin.fail()或cin.good()的值,以确保一切正常。 p>
I'm a newbie to C++. Small code sample follows:
int main(int argc, char* argv[]) {
char ch1;
int int1;
cin >> ch1;
cin >> int1;
cout << ch1 << '\n';
cout << int1 << '\n';
return 0;
}
When I run the program and input the following:
az
I get as output:
a 32767
I understand the 'a' but why the integer value of 32767? I just want to test and see what happen if instead of a numeric value assigned to int1 i used a 'z'.
I try inputting:
ax
...and I also get same results.
Now if instead of int int1
I use short int1
and run the program with input:
az
I get the output:
a 0
P.S.
sizeof(int) = 4
sizeof(short) = 2
I am using a 64-bit machine.
When an input stream fails to read valid data, it doesn't change the value you passed it. 'z' is not a valid number, so int1 is being left unchanged. int1 wasn't initialized, so it happened to have the value of 32767. Check the value of cin.fail() or cin.good() after reading your data to make sure that everything worked the way you expect it to.
这篇关于怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!