如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒

cin.getline skips the reminder of the input if the user enters larger input than the char array

本文关键字:输入 getline cin 用户 大于 char 如果 数组      更新时间:2023-10-16

我正在尝试将数据输入到包含字符数组成员和 int 成员的结构数组中,如下所示:

int main(){
typedef struct {
char name[10];
int age;
}Student;
Student students[3];
for (i=0;i<N;i++){
cout<<"n Enter name of student : "<< i+1<<" " ;
cin.getline(students[i].name, 10);
cout<<"n Enter age of student : "<< i+1<<" ";
cin>>students[i].age ;    
}

但是,如果我输入的名称超过 10 个字符(用户可能会这样做(,则其余的输入命令将被忽略。

我尝试添加cin.ignore()但没有帮助。

我尝试将gets(students[i].name);fflush(stdin);一起使用,但这也没有帮助。

我不能使用std::string.有什么建议吗?

我只是想起了std::istream::getline()的文档:

如果

函数没有提取任何字符(例如,如果计数<1(,则执行 setstate(failbit(。

这意味着在输入超过 10 个字符(包括 EOL(后,std::cin处于失败状态。因此,如果不对此做出反应,就无法提取更多的输入。

您可以通过以下方式检查std::istream::fail().

若要清除失败状态,可以使用std::istream::clear()

在准备MCVE时,我意识到了另一个弱点:

std::istream::getline()与输入流运算符混合>>需要特别注意,因为

  • getline()读取直到行分隔符的末尾,但
  • operator>>读取实际值之前的空格(包括行尾(。

因此,ignore()应在错误后使用getline()丢弃行的其余部分,但ignore()应始终在std::cin >> students[i].age后使用以消耗行尾,至少。

所以,我想出了这个:

#include <iostream>
int main()
{
const unsigned N = 3;
const unsigned Len = 10;
struct Student {
char name[Len];
int age;
};
Student students[N];
for (unsigned i = 0; i < N; ++i) {
std::cout << "Enter name of student " << i + 1 << ": ";
std::cin.getline(students[i].name, Len);
if (std::cin.fail()) {
std::cerr << "Wrong input!n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
std::cout <<"Enter age of student : " << i + 1 << " ";
std::cin >> students[i].age;
if (std::cin.fail()) {
std::cerr << "Wrong input!n";
std::cin.clear();
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
// check read
std::cout << "nStudents:n";
for (unsigned i = 0; i < N; ++i) {
std::cout << i + 1 << ".: "
<< "name: '" << students[i].name << "'"
<< ", age: " << students[i].age << "n";
}
}

输入/输出:

Enter name of student 1: Johann Sebastian
Wrong input!
Enter age of student 1: 23
Enter name of student 2: Fred
Enter age of student 2: 22
Enter name of student 2: Fritz
Enter age of student 2: 19
Students:
1.: name: 'Johann Se', age: 23
2.: name: 'Fred', age: 22
3.: name: 'Fritz', age: 19

科里鲁的现场演示