考虑以下 2 个代码片段:
案例一:
#include <iostream>
int main()
{
int i=0;
char c='a';
i=c;
cout << i << endl; //Retuens ASCII value of 'a'
return 0;
}
案例二:
#include <iostream>
int main()
{
cout << "Enter integer value" << endl;
int i=-1;
cin >> i; //Assume user enters 'a'
cout << i << endl; //prints -1 on screen
return 0;
}
在情况 1 中,当我们使用赋值时,'a'
的 ASCII 等价物被分配给 int i
,但在情况 2 中 int i
是 -1
。为什么两种情况下的行为都不同?是设计使然吗?当为整数变量输入字符时,是否可以(使用标准函数)使用 cin
输入 ASCII 值?
//我知道 cin 失败了。我想知道的是:如果赋值正确分配了 ascii 值,为什么在输入 char 时 cin 失败?
最佳答案
如果你输入'a'
,那么cin >> i
会失败,因为i
的类型是int
。所以它打印的只是垃圾值。
你可以通过写这个来检查:
if ( cin >> i )
{
cout << i << endl; //on successful read this will be printed!
}
else
{
cout << "cannot read 'a' from input stream";
}
它将打印:
cannot read 'a' from input stream
关于c++ - cin 和赋值的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6675393/