我在這個基本的C++測驗程序中遇到了一些小麻煩。在主函數中,我讓用戶輸入他/她的名字,並將該字符串傳遞給下一個函數take_quiz。但是,我注意到如果我在其中包含一個名稱(如名和姓),會發生錯誤。出於某種原因,第二個單詞中的字母數量會產生相同數量的「請輸入有效答案(a,b,c,d)」。我認爲這很奇怪,因爲只有在take_quiz中的變量的第一個cin後面使用內聯函數valCheck時纔會發生提示。我需要一些幫助來確定問題並予以糾正。謝謝!基於字符串長度的測驗函數中的錯誤
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]);
參見[此線索](http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces)關於如何使用'cin'獲得包含空格的文本流。 – Carlton
'valCheck()'不會返回任何東西 - 根據簽名它需要返回一個'char'值。如果你的字符串包含換行符,你希望使用'std :: getline(std :: cin,str);'而不是'cin'。 – Constantin
嘿Constantin std :: getline(std :: cin,str)函數效果很好!但是我不認爲我需要valCheck返回任何東西,因爲它接受一個引用,並且它正在改變輸入。糾正我,如果我錯了 – CZou48