为什么cin.getline()在这里不起作用? [英] Why cin.getline() does not work here ?

查看:231
本文介绍了为什么cin.getline()在这里不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class AbC
{
public:
	void SetData()
	{			
		cout<<"Enter Text : ";
		std::cin.getline(Text,29);		
		cout<<"Enter Age : ";
		cin>>Age;
	}
public:
	char Text[30];
	float Age;
};
void main()
{
	int x;
	std::cin>>x;// when write this statment i can not insert text with cin.getline() , and when i delete this statment cin.getline() work

	AbC obj;
	obj.SetData();

}

推荐答案

在cin>> x之后,输入流包含换行符。

getline读取输入流直到找到换行符号。



After cin>>x, input stream contains new line character.
getline read input stream to until a new line character found.

std::cin.getline(Text,29);

返回,因为它在输入流中找到了剩余的'\ n'字符。



在cin>> x之后,通过以下代码清除输入流,getline将起作用。

returns because it found the remaining '\n' character in the input stream.

After cin>>x, clear the input stream by the following code, and getline will work.

int x;
	std::cin>>x;
std::cin.ignore(std::cin.rdbuf()->in_avail()); // clear the input stream


这篇关于为什么cin.getline()在这里不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆