可能重复: getline不要求输入?
事情发生在我的程序。 下面是一些命令集:
cout< 输入学生的全名:; // cin name getline(cin,fullName); cout<< \ nAge:; // cin age int age; cin>>年龄; cout<< \\\Father's Name:; // cin father name getline(cin,fatherName); cout<< \\\Permanent Address:; // cin permanent address getline(cin,permanentAddress);当我尝试与整个代码一起运行此代码片段。 p>
输出: 输入学生的全名:年龄:20 父亲姓名:永久地址:xyz
程序没有问我的全名,直接问我的年龄。它跳过父亲的名字也要求永久地址。 可能是什么原因?
我很难发布整个代码,因为它太大了。
解决方案由于您尚未发布任何代码。
使用 getline 时常见的问题是 cin c> 是 getline 不忽略前导空格字符。
code> cin>> , getline()将此换行符看作前导空格,
调用
在调用 getline()之前调用
使用一个虚拟调用 getline()来使用 cin>>
Possible Duplicate: getline not asking for input?
There is some unique thing happening in my program. Here are some set of commands :
cout << "Enter the full name of student: "; // cin name getline( cin , fullName ); cout << "\nAge: "; // cin age int age; cin >> age ; cout << "\nFather's Name: "; // cin father name getline( cin , fatherName ); cout << "\nPermanent Address: "; // cin permanent address getline( cin , permanentAddress );When i try to run this snippet along with the whole code.The output program works like :
output: Enter the full name of student: Age: 20 Father's Name: Permanent Address: xyzIf you notice ,the program didn't ask me the full name and went on directly to ask me the age.Then it skips the father's name also and asks the permanent address. What could be the reason for this ?
It is difficult for me to post the whole code because it is too large.
解决方案Since you have not posted any code. I am going to take a guess.
A common problem while using getline with cin is getline does not ignore leading whitespace characters.
If getline is used after cin >>, the getline() sees this newline character as leading whitespace, and it just stops reading any further.
How to resolve it?
Call cin.ignore() before calling getline()
Or
make a dummy call getline() to consume the trailing newline character from the cin >>
更多推荐
getline不能正常工作?可能是什么原因?
发布评论