getline(cin, lname);为什么lname不出

mingst1954 2009-12-31 01:13:32
#include <iostream>
#include <string>
#include <cstring>

int main()
{
using namespace std;
cout<<"Enter your first name: ";
char fname[5];
cin>>fname;
cout<<"Enter your last name: ";
string lname;
getline(cin, lname);
// 为什么lname显示不出来?

cout<<"Here's the information in a single string: "<<lname<<", "<<fname<<endl;

return 0;
}
...全文
85 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mingst1954 2009-12-31
  • 打赏
  • 举报
回复
非常感谢!
小小攻城师 2009-12-31
  • 打赏
  • 举报
回复
缓冲区问题。你需要用sync()先把缓冲区清空。
你输入fname之后又一个回车,getline默认是以回车做结束
getline遇到回车,肯定就不会接受这个lname了。
也可以这样做。
#include <iostream>
#include <string>
#include <cstring>

int main()
{
using namespace std;
cout<<"Enter your first name: ";
char fname[5];
cin>>fname;
cout<<"Enter your last name: ";
string lname;
getline(cin, lname);
getline(cin, lname);
// 为什么lname显示不出来?

cout<<"Here's the information in a single string: "<<lname<<", "<<fname<<endl;

return 0;
}
用另一个getline接受回车。但是不推荐这样做,标准做法在楼上,用sync清空缓冲区
你可以找本书看看标准输出输出那一块,一般都有讲
或者直接google cin.sync(),我觉得也应该讲的很清楚
小小攻城师 2009-12-31
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
#include <cstring>

int main()
{
using namespace std;
cout<<"Enter your first name: ";
char fname[5];
cin>>fname;
cout<<"Enter your last name: ";
string lname;
cin.sync(); //清空缓冲区
getline(cin, lname);
// 为什么lname显示不出来?

cout<<"Here's the information in a single string: "<<lname<<", "<<fname<<endl;

return 0;
}
mingst1954 2009-12-31
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 buptzwp 的回复:]
fflush(stdin);
getline(cin, lname);前加fflush(stdin);
[/Quote]

为什么getline(cin,lname);
最后输出的时候是空两行?
buptzwp 2009-12-31
  • 打赏
  • 举报
回复
fflush(stdin);
getline(cin, lname);前加fflush(stdin);
taodm 2009-12-31
  • 打赏
  • 举报
回复
呃,因为你忘了 char fname[5];
cin>>fname;
这句输入的时候你自己敲了回车了。
cin.sync();
string lname;
getline(cin, lname);

64,666

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧