while 循环运行,无论输入是否正确
While loop runs regardless of correct/incorrect input
我正在处理这个程序,由于某种原因,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 循环将进入循环,如果未输入正确的答案,则继续循环
相关文章:
- 检查输入是否不是整数或数字
- 检查TCHAR数组输入是否为带符号整数C++
- 如何检查输入是否有效?
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 有没有办法检查用户输入是否是数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 确定用户输入是否为带C++的回文
- isdigit() 和 isalnum() 给出错误,因为输入是一个常量字符并且无法转换。其他可能查看输入是否为数字的方法?
- 检查输入是否为字母数字时的逻辑错误
- 如何在 while 循环C++中检查 int 输入是否为空或用户按 Enter 键
- C++ 检查 cin 的输入是否正确数据
- 如何检查字符串输入是否为有效的双精度
- 检查用户输入是否正确的函数不起作用
- 检查leandit输入是否具有正确的格式QT 5 C
- 确定输入是否为整数C++时出现问题
- 验证用户输入是否有效 [从 'char' 到 'char*' 的转换无效]
- 方法应将 R 值引用作为输入是否有任何正当理由
- 检查输入是否为数字,否则将其视为字符
- 检查用户输入是否按字母顺序排列