我正在使用 while 循环,我希望用户输入 r、R、p 或 P。但是当我添加多个条件时,例如:
while ((userInput != "r") || (userInput != "p" || (userInput != "R") || (userInput!= "P")) {
cout << "Please enter a valid option" << endl;
cin >> userInput;
}
我的程序将永远陷入循环。好像我是这样输入的:
while (userInput != "r") {
cout << "Please enter a valid option" << endl;
cin >> userInput;
}
如果用户输入“r”,我的代码将退出 for 循环 那么为什么第一段代码不起作用呢?我没有错误,这意味着它必须是一个逻辑错误,但我不明白。如何在 for 循环中获得更多条件并使其工作?
最佳答案
您需要使用 &&
而不是 ||
因为使用 ||
时 while
中的条件是总是 true
。例如,当您写“r”时,条件 userinput != r
为假,但其余条件为真,使用 &&
所有表达式都变为 false
和 while
结束。
关于c++ - 如何在一个 while 循环中获取多个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47402665/