C++学生就业信息链表代码字符串首字符不显示原因及解决方法
问题分析与解决
根本原因
该问题完全由cin.ignore()的错误调用导致:
cin.ignore()的作用是丢弃输入缓冲区的第一个字符,代码中在每一次getline()读取字符串前都调用了该方法,属于滥用:- 首次进入录入循环时输入缓冲区为空,第一次
cin.ignore()会直接吃掉用户输入的学生姓名首字符 - 后续每个
getline()前的cin.ignore()会依次吃掉分支、院校、岗位名称的首字符 - 只有在使用
cin >>读取数值(薪资、联系方式、是否继续添加标识)后,输入缓冲区会残留换行符\n,才需要清理缓冲区避免后续getline()读到空内容,其余场景不需要调用cin.ignore()
- 首次进入录入循环时输入缓冲区为空,第一次
- 该逻辑完全匹配你给出的运行结果:第一个学生的所有字符串都丢失首字符,第二个学生录入前
cin >> add残留的换行被第一个cin.ignore()吃掉,所以姓名正常,其余字符串仍然丢失首字符。
解决方法
修改create()函数,仅保留数值读取后、下一次getline()调用前的缓冲区清理逻辑,删除其余所有cin.ignore()调用:
// 如需更稳妥的缓冲区清理,可额外引入头文件 #include <limits> void list :: create() { node *temp,*ptr; int add=0; do { temp=new node; cout<<"\nEnter name of Student hired :- "; getline(cin,temp->stud_name); cout<<"Branch of the Student hired :- "; getline(cin,temp->stud_branch); cout<<"Enter the name of the Institute of hired Student :- "; getline(cin,temp->stud_coll); cout<<"Enter the post at which student is hired :- "; getline(cin,temp->post_name); cout<<"Enter the Package given to the hired student(in LPA) :- "; cin>>temp->stud_pac; cout<<"Enter contact number of the Student hired :- "; cin>>temp->stud_con; temp->next=NULL; if(head==NULL) { head=temp; } else { ptr=head; while(ptr->next!=NULL) { ptr=ptr->next; } ptr->next=temp; } cout<<"Type 1 to Insert more records :- "; cin>>add; // 仅在此处清理cin>>add残留的换行符,供下一轮循环的getline使用 // 更稳妥的写法:cin.ignore(numeric_limits<streamsize>::max(), '\n'); 可清理所有残留直到换行 cin.ignore(); }while(add==1); }
内容的提问来源于stack exchange,提问作者Anon2002
相关产品推荐
相关产品推荐

