getline不能正常工作?可能是什么原因?

编程入门 行业动态 更新时间:2024-10-19 15:45:32
本文介绍了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不能正常工作?可能是什么原因?

本文发布于:2023-11-28 07:02:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不能正常   工作   getline

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!