所以我是C++新手,我正在上入门课程,明天的任务是编写一个有 5 个问题的程序,有些是多项选择题,有些是真的或错的。
现在我正在研究第一个多项选择题,它必须有 4 个可能的答案(a、b、c、d),并有条件:
- 如果用户输入正确的字母选择,则继续下一个问题。
- 如果用户输入了错误的字母选择,它会告诉用户他们错了,并再次询问他们问题。 如果用户输入除
- 4 个字母以外的任何其他内容,它会显示无效的输入错误,并再次询问他们问题。
2 和 3 将发生,直到他们输入正确答案。
我正在尝试使用一个while循环(我认为这是要走的路?),然后在里面有一个嵌套的if/else语句。
我遇到的问题是,Q1 字符串变量在输入时一开始就实例化了,然后就无法更改了。使循环要么通过(如果回答正确)要么无限重复。
我怎样才能刷新变量以使其不重复,或者以一种完全不同的更好方式执行此操作?就像我说的我是新人,所以如果我做了愚蠢或错误的事情,请原谅我!
这是我当前的代码,到目前为止只有一个问题:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string Q1;
cout << "How many ounces are in 1 cup?" << endl;
cout << "A. 12 nB. 8 nC. 16 nD. 4" << endl;
cin >> Q1;
while (Q1 != "B") {
if (Q1 == "A" || Q1 == "C" || Q1 == "D"){
cout << "Your selected answer " << Q1 << " is incorrect, please select another answer" << endl;
}
else {
cout << "Your answer is invalid, please enter either A, B, C, or D." << endl;
}
}
cout << "Correct! There are 8 ounces in one cup" << endl;
}
在你的代码中,你有一个无限循环。您再也不会要求用户输入。您需要在循环末尾添加cin >> Q1
:
while (Q1 != "B") {
if (Q1 == "A" || Q1 == "C" || Q1 == "D"){
cout << "Your selected answer " << Q1 << " is incorrect...
}
else {
cout << "Your answer is invalid, please enter either...
}
cin >> Q1;
}
这是一个活生生的例子。
while (cin>>Q1)
{
if(Q1 == "B")
{
cout << "Next questionn";
break;
}
if (Q1 == "A" || Q1 == "C" || Q1 == "D"){
cout << "Your selected answer " << Q1 << " is incorrect, please select another answer" << endl;
}
else {
cout << "Your answer is invalid, please enter either A, B, C, or D." << endl;
}
}
这不是100%正确的答案,但应该引导您朝着正确的方向前进。我已经使用break;
退出循环,但您不必这样做。
干杯