我正在尝试将数据输入到包含char数组成员和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()
:
如果该函数未提取任何字符(例如,如果count <1),则执行setstate(failbit)。
这意味着在输入超过10个字符(包括EOL)之后,std::istream::getline()
处于失败状态。因此,如果不对此做出反应,则无法提取更多输入。
您可以使用std::cin
进行确认。
要清除失败状态,可以使用std::istream::fail()
。
[准备MCVE时,我意识到了另一个缺点:
与输入流运算符std::istream::fail()
混合std::istream::clear()
需要特别注意,因为
std::istream::clear()
读取直到行定界符的结尾,但是std::istream::getline()
读取实际值之前的空格(包括行尾)。因此,>>
中的错误后应该使用getline()
来丢弃其余的行,但是至少在operator>>
之后的总应使用ignore()
以至少消耗行的末尾。
所以,我想到了:
getline()
输入/输出:
ignore()
std::cin >> students[i].age