XIAODI
XIAODI

Reputation: 109

CPP function can't get right output

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("? ");
    }
}

When I input l, the output is load complete. But then I input +, it still outputs load complete. Why does it not output add complete?

http://ideone.com/JCDdXk

Upvotes: 0

Views: 90

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

You are declaring two variables called oper.

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

The second line marked HERE declares a new variable in the current scope rather than updating the existing one in the containing scope. Change it to:

oper = readString("? ");

Upvotes: 6

Related Questions