我正在为我的c ++类开发一个项目,但是我对如何正确地验证输入以确保输入正确之前有些困惑。以下是旨在允许用户输入学生姓名和考试成绩的功能。我的问题涉及第6行的“ getline”和第11行的(!(cin >> score [i] [j]))。
对于getline,我需要一种方法来检查是否仅输入字母字符。 对于(!(cin >>分数...))如果用户输入一个整数,后跟一个字符(即“ 8a”),则不会将其检测为输入错误。有什么办法可以解决这个问题?
编辑:感谢“ David Rankin-ReinstateMonica”,我提出了部分解决方案。 我使用以下代码更改了getline验证,使其仅接受字母字符,空格和句点:
while (!(names[i].find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. ") == string::npos && !names[i].empty())) // check to make sure there are no invalid characters and names[i] isnt blank
{
cout << "Enter the student's name: ";
getline(cin, names[i]); // Allow for full name entry (first, middle, and last names)
if (!(names[i].find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. ") == string::npos && !names[i].empty())) // another check, outputs error msg if getline value is invalid
cout << "Names must consist of letters, periods, or spaces. \n";
}
但是,我仍然对如何验证(!(cin >> score [i] [j]))部分感到困惑。是否可以为score [i] [j]创建一个临时的char数组,然后测试char数组的每个元素是否为数字?还是有一些更简单的方法?
void getNameScore(string names[], double score[NGS_SIZE][S_SIZE], char grade[])
{
for (int i = 0; i < NGS_SIZE; i++)
{
cout << "Enter the student's name: ";
getline(cin, names[i]); // Allow for full name entry (first, middle, and last names)
double total = 0;
for (int j = 0; j < S_SIZE; j++)
{
cout << "Enter " << names[i] << "'s test " << j + 1 << " score: ";
while (!(cin >> score[i][j]) || score[i][j] < 0 || score[i][j] > 100) // input validation 0 to 100 as well as cin data type error checking
{
cout << "Enter a number between 0 and 100: ";
cin.clear(); // clear error flags when a non-integer value is entered in line 38
cin.ignore(10000, '\n'); // clear input buffer
}
total += score[i][j];
}
cout << endl;
cin.ignore(10000, '\n'); // clear getline buffer on line 32
double avg = total / S_SIZE;
if (avg >= 90)
grade[i] = 'A';
else if (avg >= 80)
grade[i] = 'B';
else if (avg >= 70)
grade[i] = 'C';
else if (avg >= 60)
grade[i] = 'D';
else
grade[i] = 'F';
}
}