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
?
答案 0 :(得分:6)
您正在声明名为oper
的两个变量。
int main()
{
string oper = readString("? "); //HERE
while (oper != "Q")
{
string oper = readString("? "); //HERE
}
}
标记为HERE
的第二行在当前范围内声明一个新变量,而不是更新包含范围中的现有变量。将其更改为:
oper = readString("? ");