您好我遇到了getline()的未知问题。我的程序应该是cout一个提示,然后getline()应该在用户输入中读取但由于某种原因每次我运行它只是couts提示并跳到下一个提示,不允许我输入任何东西。我会发布代码,希望你们能提供一些建议。
int main()
{
int students = 0;
students = getStudents(students);
int quizzes = 0;
quizzes = getQuizzes(quizzes);
string studentArray[50];
int* quizArray = new int[quizzes];
double* studentAverage = new double[students];
string studentName = "";
for(int i = 0; i < students; i++)
{
cout << "Enter the students name: ";
getline(cin, studentName);
studentArray[i] = studentName;
cout << studentName;
for(int j = 0; j < quizzes; j++)
{
cout << "Enter quiz " << j+1 << ":";
cin >> quizArray[j];
}
studentAverage[i] = calculateAvergage(quizArray,quizzes);
cout << studentArray[i];
cout << studentName;
}
cout << endl;
cout << "Student Quiz Average" << endl << endl;
cout << "---------------------------------" << endl << endl;
for(int i = 0; i < students; i++)
{
cout << studentArray[i];
cout << setw(10) << studentAverage[i] << endl << endl;
}
}
int getStudents(int students)
{
cout << "How many students? ";
cin >> students;
cout << endl;
if(students > 50)
{
cout << "Invalid number of students, enter a number less than 50: ";
cin >> students;
cout << endl;
}
return students;
}
int getQuizzes(int quizzes)
{
cout << "How many quizzes? ";
cin >> quizzes;
cout << endl;
if(quizzes > 10)
{
cout << "Invalid number of quizzes, enter a number less than 10: ";
cin >> quizzes;
cout << endl;
}
return quizzes;
}
double calculateAvergage(int quiz_array[],int num_quizzes)
{
double average = 0;
for(int i = 0; i < num_quizzes; i++)
{
average = quiz_array[i] + average;
}
average = (average/num_quizzes);
return average;
}
答案 0 :(得分:0)
从像这样的流中读取单个值
cin >> quizzes;
不消耗行尾字符(或尝试阅读quizzes
后遗留的任何其他无效字符),因此下一次调用getline
将继续从同一行读取输入(通常你会看到在阅读quizzes
后该行为空,所以getline
最终没有读到任何内容。)
如果在阅读quizzes
后使用以下内容,您的计划应该有效:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
或者您只需以与其他值相同的方式阅读studentName
std::cin >> studentName;
与对operator>>
的所有调用一样,这会删除所有前导空格,包括换行符。