Click here to Skip to main content
13,152,454 members (36,773 online)
Rate this:
 
Please Sign up or sign in to vote.
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 2-Feb-13 5:17am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

You should flush std::cin buffer after your integer value was read:
//...
std::cin >> namecount;
std::cin.sync();
std::cout << "Enter your name: " << std::endl;
//...

or ignore end of line
    //...
    std::cin >> namecount;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Enter your name: " << std::endl;
    //...
</std::streamsize>
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Hi,

I have called cin.Ignore(), please refer the below,
#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
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web04 | 2.8.170924.2 | Last Updated 2 Feb 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100