C++ 而不管输入是否正确,循环都会运行

C++ 而不管输入是否正确,循环都会运行,c++,C++,我有一个我正在处理的程序,由于某种原因,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_answ

我有一个我正在处理的程序,由于某种原因,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;
}
#包括
使用名称空间std;
int main(){
常数int size=5;
字符答题纸[size]={'B','D','A','A','C'};//A','B','A','C','D','B','C','D','A','D','D','C','B','D','A','D','A';
char student_答案[大小];
答案;

对于(int i=0;i
answer!=“A”| answer!=“B”
,对于
answer
的任何值,都始终为真。
你是说
&&
而不是
|

你要寻找的条件是

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;

}
while(答案!=“A”|答案!=“B”|答案!=“A”|答案!=“B”)
{
难道你忘了C和D(可能是打字错误):

也许你想要:

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.
}

:)我觉得这些标题很有趣。请阅读“
没有按应有的方式工作”as“没有按我预期的方式工作”呃,我的英语不是最好的。是的,这是一个打字错误,我不好。
const std::string allowable_answers = "ABCD";
//...
while (allowable_answers.find(answer) == std::string::npos)
{
   // answer is not in the allowable set.
}