所以我是C的新手,我正在上入门课程,明天的任务是编写一个有5个问题的程序,一些多选,一些正确或错误。
现在我正在做第一个选择题,它必须有4个可能的答案(a, b,c,d),条件是:
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
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 question\n";
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%正确的答案,但应该引导您朝着正确的方向前进。我使用了Rest;
退出循环,但您不必这样做。
干杯