while 循环运行,无论输入是否正确

While loop runs regardless of correct/incorrect input

本文关键字:输入 是否 循环 运行 while      更新时间:2023-10-16

我正在处理这个程序,由于某种原因,while 循环没有按照我预期/期望的方式运行。

#include <iostream>
using namespace std;
int main() {
const int size = 5;
char answer_sheet[size] = {'B','D','A','A','C'}; //'A','B','A','C','D','B','C','D','A','D','C','C','B','D','A'};
char student_answer[size];
char answer;

for(int i=0;i<size;i++)
{
    cout << i+1 << ": ";
    cin >> answer;
    cout << endl;
    while(answer != 'A' || answer != 'B' || answer != 'C' || answer != 'D')
    {
        cout << "You must enter either A, B, C, or D" << endl;
        cout << i+1 << ": ";
        cin >> answer;
        cout << endl;
    }
    student_answer[i] = answer;
}
return 0;
}

我正在输入字符 A、B、C 或 D,当我以正确的方式输入它时,除非我输入错误的字符,否则我不应该进入 while 循环。

我似乎无法弄清楚问题所在。

谢谢

对于

answer 的任何值,answer != 'A' || answer != 'B'始终为真。你的意思是&&而不是||

你忘记了C和D(可能是错别字):

while(answer != 'A' || answer != 'B' || answer != 'A' || answer != 'B')

也许你想要:

while (answer != 'A'
       && answer != 'B'
       && answer != 'C'
       && answer != 'D')
{
}

另一种方法:

const std::string allowable_answers = "ABCD";
//...
while (allowable_answers.find(answer) == std::string::npos)
{
   // answer is not in the allowable set.
}

您要查找的条件是

while(answer != 'A' && answer != 'B' && answer != 'C' && answer != 'D')

在每种情况下,|| 都应该是 &&,你也不应该检查"C"或"D"

首先,为什么不使用do/while循环而不是while循环。其次,你有

while(answer != 'A' || answer != 'B' || answer != 'A' || answer != 'B')
{
    cout << "You must enter either A, B, C, or D" << endl;
    cout << i+1 << ": ";
    cin >> answer;
    cout << endl;
}

如果 A、B、C、D 不是输入,程序不应该循环吗?如果 A、B、A、B 不是答案,你就可以循环这个。 do/while 循环将进入循环,如果未输入正确的答案,则继续循环