Click here to Skip to main content
15,887,288 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();

}
Posted
Comments
CPallini 4-Jun-13 14:39pm    
It works on my system (Windows 8, Visual Studio 2012).
Did you press ENTER after inserting x?
Anderso0on 4-Jun-13 14:58pm    
i use Windows 8, Visual Studio 2012 and it does not work

1 solution

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

C++
std::cin.getline(Text,29);
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.
C++
int x;
	std::cin>>x;
std::cin.ignore(std::cin.rdbuf()->in_avail()); // clear the input stream
 
Share this answer
 
Comments
Anderso0on 4-Jun-13 14:54pm    
please explain what is going on in the code ?
Santhosh G_ 4-Jun-13 15:01pm    
For getline, The delimiting character is the newline character ('\n'). If a pending '\n' in input stream,cin then getline immediately returns.
After cin>>x the '\n' is remained in the input stream.
http://www.cplusplus.com/reference/istream/istream/getline/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900