问题描述
可能的重复:
getline 不要求输入?
在我的程序中发生了一些独特的事情.下面是一些命令集:
cout <<"请输入学生全名:";//名称getline( cin , fullName );cout<<"
年龄:";//cin年龄年龄;cin >>年龄 ;cout<<"
父亲姓名:";//cin 父亲的名字getline(cin,fatherName);cout<<"
永久地址:";//cin 永久地址getline(cin,permanentAddress);
当我尝试与整个代码一起运行此代码段时.输出程序的工作原理如下:
输出:
输入学生全名:年龄:20父亲姓名:永久地址:xyz
如果你注意到,程序并没有问我全名,而是直接问我年龄.然后它也跳过了父亲的名字并询问了永久地址.这可能是什么原因?
我很难把整个代码贴出来,因为它太大了.
由于您还没有发布任何代码.我来猜一猜.
使用 getline
和 cin
时的一个常见问题是 getline
不会忽略前导空白字符.
如果在 cin >>
之后使用 getline,getline()
会将此换行符视为前导空格,并且它只会停止进一步读取.>
如何解决?
在调用getline()
cin.ignore()
或者
进行虚拟调用 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 << "
Age: "; // cin age
int age;
cin >> age ;
cout << "
Father's Name: "; // cin father name
getline( cin , fatherName );
cout << "
Permanent 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: xyz
If 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 无法正常工作?可能是什么原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!