当一个字符串值在c ++中为整数变量赋值时会发生什么?

say*_*han 6 c++ variables

我刚开始学习c ++(原谅我的noobish查询).这是我作为练习编写的一些代码:

#include<iostream>

int main()
{
    using namespace std;

    int foo;
    cin >> foo;

    int bar;

    cin >> bar;
    cout << "foo plus bar is " << foo+bar<< endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在,当输入都是数字时,此代码完全正常.但是当我为第一个输入输入一个字符串时(只是为了看看会发生什么),程序不会向我询问第二个输入,cout结果是foo plus bar is 0.我想知道的是,cin当我将字符串分配给整数变量时,为什么程序会跳过我的第二个.感谢您的帮助.

小智 7

流具有内部状态.如果输入失败,则设置状态以指示错误,并且所有其他输入将失败,除非该状态被清除.

在你的情况下,你应该初始化foo和bar为零.

测试流状态:

if( ! (cin >> foo)) {
    // Error
}
Run Code Online (Sandbox Code Playgroud)

与酒吧相同

如果已解决输入失败,则可以使用它cin.clear()来清除错误状态.