在 do...while 中放置一个开关
所以我有一个 do...while 语句,除非用户输入四件事之一,否则应该重复该语句。这四件事有一个中断,它们将控制 while 的变量设置为 true,默认值为 false。如果用户没有输入四个答案之一,则该变量将保持 false,这将使 do...while 重新开始。事实并非如此。
#include <string>
#include <iostream>
using namespace std;
int main()
{
int q5_answer = 1;
int q5_answerU;
int total_score;
bool q5_valid = false;
//Question_5:
do
{
cout << "Question 5 (#1 is correct)" <<endl;
cout << "1.) Answer 1" <<endl;
cout << "2.) Answer 2" <<endl;
cout << "3.) Answer 3" <<endl;
cout << "4.) Answer 4" <<endl;
cin >> q5_answerU;
switch (q5_answerU)
{
case 1:
cout << "Correct!" <<endl;
q5_valid = true;
(total_score = total_score + 1);
break;
case 2:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
case 3:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
case 4:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
default:
cout << "Invalid answer" <<endl;
}
} while (q5_valid = false);
}
So I have a do... while statement that is supposed to repeat unless the user enters one of four things. Those four things have a break and they set the variable that controls the while to true, where the default is false. If the user does not enter one of the four answers, the variable will stay false, which should make the do...while start again. It doesn't.
#include <string>
#include <iostream>
using namespace std;
int main()
{
int q5_answer = 1;
int q5_answerU;
int total_score;
bool q5_valid = false;
//Question_5:
do
{
cout << "Question 5 (#1 is correct)" <<endl;
cout << "1.) Answer 1" <<endl;
cout << "2.) Answer 2" <<endl;
cout << "3.) Answer 3" <<endl;
cout << "4.) Answer 4" <<endl;
cin >> q5_answerU;
switch (q5_answerU)
{
case 1:
cout << "Correct!" <<endl;
q5_valid = true;
(total_score = total_score + 1);
break;
case 2:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
case 3:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
case 4:
cout << "Incorrect" <<endl;
q5_valid = true;
break;
default:
cout << "Invalid answer" <<endl;
}
} while (q5_valid = false);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
while 内的条件是“意外”赋值,而不是比较。它需要读取
while (q5_valid == false)
或更惯用的while (!q5_valid)
。The condition inside the
while
is an "accidental" assignment, not a comparison. It needs to readwhile (q5_valid == false)
or more idiomaticwhile (!q5_valid)
.这不是布尔表达式:
它将变量 q5_valid 设置为
false
并返回false
。将其替换为:或
哪些是相同的。前者的可读性更好。
This is not a boolean expression:
It sets the variable q5_valid to
false
and also returnsfalse
. Replace it by:or
Which are the same. The former is better for readability.