请考虑以下2个代码段:
情况1:
#include <iostream>
int main()
{
int i=0;
char c='a';
i=c;
cout << i << endl; //Retuens ASCII value of 'a'
return 0;
}
Run Code Online (Sandbox Code Playgroud)
案例2:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在案例1中,当我们使用分配的ASCII相当于'a'被分配到int i,但在第2种情况int i是-1.为什么两种情况下的行为都不同?它是按设计的吗?cin当为整数变量输入字符时,是否可以(使用标准函数)输入ASCII值?
//我明白cin失败了 我想知道的是:为什么cin在输入char时失败,如果赋值正确分配ascii值?
如果输入'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";
}
Run Code Online (Sandbox Code Playgroud)
它会打印出来:
无法从输入流中读取"a"