关于两次输入getline的困惑

u010179812 2014-06-14 10:44:22
#include <iostream>
#include <string>
using namespace std;

int main()
{
char name[10];
cin.getline(name, 5);
cout<<"name = "<<name<<endl;

char name2[10];
cin.getline(name2, 10);
cout<<"name2[0] = "<<(int)name2[0]<<endl;


return 0;
}


上面的我输入aaaabbbb得到如下结果:

我有点不明白,为什么第二个字符串的首字符不是'b',而是空字符。

但是如果我在中间加上cin.clear();明明清空了,却得到的是'b'

#include <iostream>
#include <string>
using namespace std;

int main()
{
char name[10];
cin.getline(name, 5);
cout<<"name = "<<name<<endl;

cin.clear();

char name2[10];
cin.getline(name2, 10);
cout<<"name2[0] = "<<(int)name2[0]<<endl;


return 0;
}


我同样进行上面的输入,得到的结果为


不懂,请帮我解惑吧。
...全文
215 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
adamevi 2014-06-14
  • 打赏
  • 举报
回复
cin.getline(name, 5); 当你出入的字符超过4个时,failbit被设定1,cin不可用,所以下面就输入不进去了;当使用cin.clear()清除错误状态,将failbit设置为0,才可以继续读取队列中的内容。
zhjianjun 2014-06-14
  • 打赏
  • 举报
回复
也可以找中文第5版对应章节
zhjianjun 2014-06-14
  • 打赏
  • 举报
回复
以下应该有帮助: C++ Primer Plus 6th edition Stephen Prata.pdf Page 129 Why use get() instead of getline() at all? First, older implementations may not have getline(). Second, get() lets you be a bit more careful. Suppose, for example, you used get() to read a line into an array. How can you tell if it read the whole line rather than stopped because the array was filled? Look at the next input character. If it is a newline character, then the whole line was read. If it is not a newline character, then there is still130 more input on that line. Chapter 17 investigates this technique. In short, getline() is a little simpler to use, but get() makes error checking simpler.You can use either one to read a line of input; just keep the slightly different behaviors in mind. 以及17章的Input with cin。 我很少用cin,简单的略过去了,印像中提到了你出现的问题及解决办法。
u010179812 2014-06-14
  • 打赏
  • 举报
回复
谢谢大家,我再好好看看书。
SoulLove-晨曦 2014-06-14
  • 打赏
  • 举报
回复
#include <string>
using namespace std;

int main()
{
	char name[10];
	cin.getline(name, 5);
	cout << "name = " << name << endl;
	cin.clear();	// 重置 cin 输入状态
	cin.sync();	// 清除 cin 缓冲区未读取信息
	char name2[10];
	cin.getline(name2, 10);
	cout << "name2[0] = " << (int)name2[0] << endl;
	return 0;
}
cin.clear(); 并不是清除CIN缓冲区,将输入流cin中的所有状态值都重设为有效状态。 cin.sync(); 这才是真正的清除cin缓冲区,将输入流里的队列清空。

64,642

社区成员

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

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