在 while 循环中比较多个字符串

Comparing multiple strings in while loop

本文关键字:字符串 比较 while 循环      更新时间:2023-10-16

我是初学者,只是想制作一个简单的计算器,提示用户输入两个值和一个操作数。

string operand;
cin >> operand;
while (operand != "+") || (operand != "-") || (operand !=  "*")|| (operand != "/"))
{
    cout << "operand must be either'+', '-', '*', or '/'." << endl;
    cin >> operand;
}

为什么无论我在操作数中输入什么,它都会一直进入 while 循环?

你想使用&&而不是||

while ((operand != "+") && (operand != "-") && (operand !=  "*") && (operand != "/"))

使用 std::string::find_first_of

while (operand.find_first_of("+-*/") == std::string::npos)
{
   //...
}