Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++C
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
0 Sergey Alexandrovich Kryukov 499
1 OriginalGriff 461
2 sanket saxena 325
3 Tadit Dash 285
4 Abhinav S 275
0 Sergey Alexandrovich Kryukov 12,159
1 OriginalGriff 7,421
2 Peter Leow 5,061
3 Abhinav S 4,073
4 Maciej Los 3,575


Advertise | Privacy | Mobile
Web04 | 2.8.140421.2 | Last Updated 2 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid