【发布时间】:2016-05-03 21:44:14
【问题描述】:
我在使用这个基本的 C++ 测验程序时遇到了一些小问题。在主函数中,我让用户输入他/她的姓名,然后将此字符串传递给下一个函数 take_quiz。但是,我注意到如果我包含一个带有空格的名称(如名字和姓氏),则会发生错误。出于某种原因,第二个单词中的字母数量会产生相同数量的“请输入有效答案(a、b、c、d)”的显示。我认为这很奇怪,因为该提示只能在使用内联函数 valCheck 时出现,该函数位于 take_quiz 中变量的第一个 cin 之后。我需要一些帮助来识别问题并纠正它。谢谢!
inline char valCheck(char& input)
{
tolower(input);
while(input < 97 || input > 100)
{
cout << "Please enter a valid answer (a, b, c, d):" << endl;
cin >> input;
}
}
int main(int argc, char *argv[])
{
string name;
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
cin >> name;
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
void take_quiz(string name2)
{
char quiz_results[10];
system("PAUSE");
cout << "\nThe quiz will now begin.\nThis quiz covers topics such as data types, arrays, pointers, etc." << endl
<< "To answer the multiple choice questions,\nsimply input a, b, c, or d according to the given options." << endl
<< "The test will continue regardless if you enter a question wrong or right." << endl
<< "Good luck " << name2 << "!" << endl;
system("PAUSE");
cout << "\n1. What preprocessor command must one include to use the cout and cin function?" << endl
<< "\na. #include <iomanip>" << endl
<< "b. #include <iostream>" << endl
<< "c. #include <cmath>" << endl
<< "d. using namespace std;" << endl;
cin >> quiz_results[0];
valCheck(quiz_results[0]);
【问题讨论】:
-
参见this thread,了解如何使用
cin获取包含空格的文本流。 -
valCheck()不返回任何内容 - 根据签名,它需要返回char值。如果您的字符串包含换行符,您想使用std::getline(std::cin, str);而不是cin。 -
嘿康斯坦丁 std::getline(std::cin, str) 函数工作得很好!但是我认为我不需要让 valCheck 返回任何内容,因为它正在接受引用并且正在更改输入。如果我错了,请纠正我
-
@CZou48 是的,正确 - 但是您应该将签名更改为:
inline void valCheck(char& input)而不是inline char valCheck(char& input)。