CPP功能无法获得正确的输出

时间:2015-04-13 09:50:10

标签: c++ c++11

string readString(string p)
{
    string s;

    cout << p;
    cin >> s;
    return s;
}

int main()
{
    string oper = readString("? ");
    while (oper != "Q")
    {
        if (oper == "l")
            cout << "load complete" << endl;
        else if (oper == "+")
            cout << "add complete" << endl;
        string oper = readString("? ");
    }
}

当我输入l时,输出为load complete。但是我输入了+,它仍然输出load complete。为什么不输出add complete

http://ideone.com/JCDdXk

1 个答案:

答案 0 :(得分:6)

您正在声明名为oper两个变量。

int main()
{
    string oper = readString("? "); //HERE
    while (oper != "Q")
    {   
        string oper = readString("? "); //HERE
    }
}

标记为HERE的第二行在当前范围内声明一个新变量,而不是更新包含范围中的现有变量。将其更改为:

oper = readString("? ");