Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I'm using a very basic program to take in a name and print it out using Visual C++ 2012 - Program works fine like this:

int main()
{
	char name[15];
	int namecount;
	cout<<"Enter your name: "<<endl;
	cin.getline(name, 15);
	cout<<"How many letters in your name (including the space)?: "<<endl;
	cin>>namecount;
	cout<<"Your name is:"<<endl;
	for(int i=0; i<namecount;i++)
	{
		cout<<name[i];
	}
	return 0;
}

but when I try and take in the length of the name first (as below) it will take in a value for namecount and then just print "Your name is" with garbage and will not execute the cin.getline statement. Any ideas welcome.

int main()
{
	char name[15];
	int namecount;
	cout<<"How many letters in your name (including the space)?: "<<endl;
	cin>>namecount;
	cout<<"Enter your name: "<<endl;
	cin.getline(name, 15);
	cout<<"Your name is:"<<endl;
	for(int i=0; i<namecount;i++)
	{
		cout<<name[i];
	}
	return 0;
}


I know I can use a string etc but just don't get why the second version won't work.
Posted

Hi,

I have called cin.Ignore(), please refer the below,
C++
#include <iostream>
#include <conio.h>
 using namespace std;
int main()
{
	char name[15];
	int namecount;
	cout<<"How many letters in your name (including the space)?: "<<endl;
	cin>>namecount;
	cout<<"Enter your name: "<<endl;
	cin.ignore(); //added
	cin.getline(name, 15,'\n');
	cout<<"Your name is:"<<endl;
	for(int i=0; i<namecount;i++)>
	{
		cout<<name[i];
	}
	getch();
	return 0;
}</conio.h></iostream>


Best Regards
Muthuraja
 
Share this answer
 
You should flush std::cin buffer after your integer value was read:
C++
//...
std::cin >> namecount;
std::cin.sync();
std::cout << "Enter your name: " << std::endl;
//...

or ignore end of line
C++
    //...
    std::cin >> namecount;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Enter your name: " << std::endl;
    //...
</std::streamsize>
 
Share this answer
 
v2

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