c++ - cin 和赋值的区别

标签 c++

考虑以下 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/

相关文章:

c++ - 具有模板化派生类的基类纯虚函数

c++ - 如何设置 win32 api c++ 按钮背景颜色和文本颜色?

c++ - Concave GL_POLYGON不上色?

c++ - C++中以下结构实现之间的区别

c++ - (long long)x 与 C++ 中的 (long long)floor(x) 相同吗?

c++ - 如何以编程方式迭代所有 CMake 目标?

c++ - 控制 map 中元素的顺序

c++ - 在 .cpp 文件中实现 operator== 的正确方法

c++ - 在这种情况下如何添加计数器?

c++ - 对引用成员进行偏移(非 POD)