getline不能正常工作?可能是什么原因? [英] getline not working properly ? What could be the reasons?

查看:141
本文介绍了getline不能正常工作?可能是什么原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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: 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不能正常工作?可能是什么原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆