第 23 行的代码有问题。(请参阅下面的代码)
当我使用 "cin >> studentNum" 时;我没有问题,程序读取名字的一个字符串,但如果我想收集更多数据,请使用 "getline(cin, studentNum)" 来读取更多字符串就像全名一样,程序只是跳过命令并询问分数。
这是为什么呢?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int studentNum, testNum, i, j;
double sum, testScore, average;
string studentName;
i = 0;
// asking user for input
cout << "Please enter the number of students in this classroom: " << endl;
cin >> studentNum;
cout << "Now enter the number of tests each student has taken in this class: " << endl;
cin >> testNum;
while (i < studentNum)
{
cout << endl << "Now please enter the firstname of the student: " << endl;
cin >> studentName; //**My Problem is in this line ###########**
j = 0;
sum = 0;
while (j < testNum)
{
cout << "Please enter the score of each test, then hit enter: " << endl;
cin >> testScore;
sum += testScore;
j++;
}
i++;
}
}
最佳答案
我觉得你需要使用 cin.ignore
.您需要丢弃流中仍然存在的换行符。
#include <limits>
// This is not a C++11 feature, works fine in C++98/03
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, studentName);
默认情况下,operator>>
将跳过前导空格,即按 std::ctype
分类.您可以在测试程序中看到,通过使用 unsetf(std::ios_base::skipws)
关闭此行为,它将提取空白。通过使用 cin.ignore
,您可以简单地丢弃它,因为它不需要。有关详细信息,请参阅 cin and getline skipping input .
关于c++ - getline(cin, var) 问题。程序忽略命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311132/