bool getAnswer(int a);
int main ()
{
string questions[5] = {"CPU stands for 'Central Processing Unit'", "RAM stands for 'Reserved Access Main'", "HDD stands for 'Hard Drive Doubler'", "SSD stands for 'Solid State Drive'", "CPP stands for 'C Programming Plus'"};
for (int i = 0; i < 5; i++)
{
cout << "Question " << ++i << " \n";
i--;
cout << questions[i] << "\n";
cout << getAnswer(i) << endl;
}
}
bool getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
cout << "Answer " << ++a << " \n";
a--;
cout << "Enter a true or false answer: " << "\n";
cin >> input;
while (input != "T" && input != "t" && input != "F" && input != "f" && input != "True" && input != "true" && input != "False" && input != "false")
{
cout << "Invalid entry, try again!\nEnter a true or false answer: " << "\n";
cin >> input;
}
if (input == "T" || input == "t" || input == "True" || input == "true")
{
user[a] = true;
}
else if (input == "F" || input == "f" || input == "False" || input == "false")
{
user[a] = false;
}
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
}
在正确/不正确与下一个问题之间的输出中,我不断得到一个“ 0”。如何删除它们。
例如:
问题1
CPU代表“中央处理器”
答案1
输入是非题:
f
不正确!
0
问题2
RAM代表“预留访问主目录”
答案2
输入是非题:
t
不正确!
0
答案 0 :(得分:1)
您的问题在于getAnswers
的返回值
cout << getAnswer(i) << endl;
您已经在getanswer函数中输出了答案是否正确。再次使用cout输出getAnswer的返回值
您可以:
cout << "Question " << ++i << " \n";
i--;
questions[i]
getAnswer(i);
cout << endl;
或者您可以简单地停止在getAnswer
中进行输出,并返回包含消息的字符串。
std::string getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
...
...
...
if (answer[a] == user[a])
{
input = "Correct!\n";
}
else if (answer[a] != user[a])
{
input = "Incorrect!\n";
}
return input;
}
如果您那样做,则无需更改主目录中的任何内容。确保从
更改getAnswers的默认值bool getAnswer(int a);
到
std::string getAnswer(int a);
答案 1 :(得分:1)
只需删除cout << "correct"
和cout << "incorrect"
,然后将返回类型从bool
更改为std::string
。
发件人:
bool getAnswer(int a) {
...
if (answer[a] == user[a])
cout << "Correct!\n";
else if (answer[a] != user[a])
cout << "Incorrect!\n";
}
收件人:
std::string getAnswer(int a) {
...
if (answer[a] == user[a])
return "Correct!\n";
else if (answer[a] != user[a])
return "Incorrect!\n";
}
程序中发生的是函数在屏幕上打印答案(这就是函数在最后两个if
内所做的事情)。之后,您的程序将尝试打印函数返回的内容:
cout << getAnswer(i) << endl;
现在,您将getAnswer()
的返回值声明为bool
类型,但是实际上,您没有指定return语句。因此,函数返回的值可以为1或0(未定义的行为),在您的情况下为0,即您看到的值。
提示
使用std::cout
代替cout
。参见Why is “using namespace std” considered bad practice?
答案 2 :(得分:1)
您声明getAnswer()
返回一个bool
值,但是从不返回任何值。解决输出问题的一种方法是兑现此返回类型并进行更改
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
到
return answer[a] == user[a];
然后代替
cout << getAnswer(i) << endl;
做
if (getAnswer(i)) {
cout << "Correct!\n" << endl;
} else {
cout << "Incorrect\n" << endl;
}