关于getline函数的问题?

smallsky_keke 2010-07-04 05:30:35
#include <iostream>
#include <string> // make string class available
#include <cstring> // C-style string library
int main()
{
using namespace std;
char charr[20];
string str;

cout << "Length of string in charr before input: "
<< strlen(charr) << endl;
cout << "Length of string in str before input: "
<< str.size() << endl;
cout << "Enter a line of text:\n";
cin.getline(charr, 20); // indicate maximum length
cout << "You entered: " << charr << endl;
cout << "Enter another line of text:\n";
getline(cin, str); // cin now an argument; no length specifier
cout << "You entered: " << str << endl;
cout << "Length of string in charr after input: "
<< strlen(charr) << endl;
cout << "Length of string in str after input: "
<< str.size() << endl;

return 0;
}



为什么输出会显示为如下结果,有谁能解释吗?
Length of string in charr before input: 23
Length of string in str before input: 0
Enter a line of text:
hello
You entered: hello
Enter another line of text:
whar's your name
here
You entered: whar's your name
Length of string in charr after input: 5
Length of string in str after input: 16

为什么运行getline(cin, str);的时候,要输入两行并且显示出来的是第一行的内容??有谁能帮我解释一下吗?
...全文
71 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
smallsky_keke 2010-07-04
  • 打赏
  • 举报
回复
问题解决了!高手啊!
herman~~ 2010-07-04
  • 打赏
  • 举报
回复
额? mark
liutengfeigo 2010-07-04
  • 打赏
  • 举报
回复

BUG,难怪我先看这贴的时候都觉得怎么会出这样的事呢。。。
耍宝王 2010-07-04
  • 打赏
  • 举报
回复
VC6.0的BUG

网上有一个解决办法:
X:\Program Files\Microsoft Visual Studio\VC98\Include\string(注意是 string文件,不是string.h)找到165行,下面的代码从163行开始
else if (_Tr::eq((_E)_C, _D)) //163行
{_Chg = true;
// _I.rdbuf()->snextc(); // 把这一行注释掉,添加下一行.
_I.rdbuf()->sbumpc(); //添加
break;}


这里有VC6.0其它STL BUG的补丁(包括这个getline两次回车的BUG)
http://download.csdn.net/source/2042973

64,654

社区成员

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

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