如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒
cin.getline skips the reminder of the input if the user enters larger input than the char array
我正在尝试将数据输入到包含字符数组成员和 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
科里鲁的现场演示
相关文章:
- 当用户键入分隔符时,停止getline()输入
- 我有三个 getline,但是一旦编译,输入就太多了
- std::getline没有在while循环中重新请求用户输入
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 如何将 getline 与标准输入一起使用?
- 使用 cin 或 getline() 输入空值
- 使用 getline 从输入文件打印时如何忽略空白行
- 对c++中的输入使用getline函数时忽略第一个字符
- 如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒
- 虽然带有 getline 的循环不会因用户输入而结束
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- C++ - 重复 std::getline() 作为用户整数输入?
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何使用 std::in 和 getline() 检测后台进程中从 bash 注入的输入
- 使用 getline 从输入文件读取一行到输出文件
- C :使用getline从文本文件中输入,要么跳过第一行,要么将其余部分弄乱
- 使用 getline 忽略用户输入中的制表符和换行符
- 递归 cin.getline() 不想要求输入
- 如何阻止 cin.getline() 导致控制台在找不到分隔符时重复获取用户输入?
- cout在获取行输入(getline)后无法在c++中工作