getline无法正常工作?可能的原因是什么?

28

可能是重复问题:
getline不要求输入?

我的程序中发生了一些独特的事情。 以下是一组命令:

 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 );
当我尝试与整个代码一起运行此片段时,输出程序的工作方式如下所示:

enter image description here

output:

Enter the full name of student:
Age: 20

Father's Name:
Permanent Address: xyz

如果您注意到,程序没有要求我输入全名,而是直接要求我输入年龄。然后它也跳过了父亲的名字,直接问我永久地址。 这可能是什么原因呢?

由于代码太长,很难将整个代码贴出。


请将程序输出粘贴到格式化的帖子部分中。图像具有随时间消失的属性,通常会产生红色十字。 - Sebastian Mach
getline不正常工作?"select没有损坏" - sehe
3
哪些声明?int agegetline,它只接受std::string作为目标?cin的?没有理由给出负分。 - Sebastian Mach
3个回答

97

鉴于您没有发布任何代码,我猜测一下。

使用cingetline时常见问题是getline不会忽略前导空格字符。

如果在cin >>之后使用getline()getline()将看到这个换行符作为前导空格,并且停止读取任何进一步的内容。

如何解决?

在调用getline()之前调用cin.ignore()

或者

进行虚拟调用getline()以消耗来自cin >>的尾随换行符


32
给“心灵调试”点个赞。 - user703016
ignore 的问题在于你不知道需要忽略多少。最好只使用 getline 一次读取一行输入。 - Sander De Dycker
如果 (getline(cin >> ws, s2)) { getline(cin, s2); } - Ace.C

4
问题在于你混合使用了getlinecin >>输入。

当你执行cin >> age;时,它会从输入流中获取年龄,但是它会在流上留下空格。具体来说,它会在输入流上留下一个换行符,然后被下一个getline调用读取为空行。

解决方法是只使用getline来获取输入,然后解析行以获取所需的信息。

或者修复你的代码,例如执行以下操作(你仍需要自己添加错误检查代码):

cout << "Enter the full name of student: ";  // cin name
getline( cin , fullName );

cout << "\nAge: ";  // cin age
int age;
{
    std::string line;
    getline(cin, line);
    std::istringstream ss(line);
    ss >> age;
}

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );

3
在代码行 cin >> age ; 之后,输入缓冲区中仍然存在换行符 \n(因为您按下回车键来输入值),为了解决这个问题,您需要在读取整数后添加一行代码 cin.ignore();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接