Program skipping 1 line when executed

Hello! I'm new in c++ and has no mentor to turn to for
questions since I'm self-studying.I'm practicing with the simple program below that accepts a "name" and eventually will output the name before the program terminates. The main problem is when I use the int variable "n" in sample *ptr= new sample[n];.

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<string>

using namespace std;


struct sample{
string name;
};



void main()
{
	int n;
	cout<<"how many?";
	cin>>n;
	sample *ptr= new sample[n]; //if I replace "n" for a constant(i.e 4, 5 ,5) the program works but if I use "n" I get the wrong output.
	
	for(int a=0; a<n; a++)
	{
	
		cout<<"Enter Name:";
		getline(cin,ptr[a].name);  // this line skips in the first loop.
	}
	for(int a=0; a<n; a++)
	{
		cout<<ptr[a].name<<endl;
	}
	[output][/output]
	delete [] ptr;
}



Output:
how many?
input:4
Enter Name:Enter Name: //This is the problem


By the way, I'm using the variable "n" to make the program more flexible in terms of the size.
Any input will be very much appreciated. Thank you!
Last edited on
When you use the operator >> on cin, it leaves the space/newline character in the buffer. This will cause functions such as getline to return immediately. Add the following code before your call to getline:
1
2
cin.sync(); //clear the buffer
cin.clear(); //clear error state flags 
Clear first, then sync, you can't modify the state of a stream while any error flags are set.
I was also fecthed this problem earlier.But you can visit this link and download some e-books which will help you to be a pro in c++.
<a href="http://www.get-tuto.blogspot.com/2012/09/c-c-programming-language-isbasically.html">c++</a>
Hello Guys! I didn't expect to get a reply immediately thus I'm kinda late in replying. I've tried ModShop's solution and Moeljbcp's suggestion. It worked pretty fine. Thank you!

@eather, Thanks for the link, more resources means more knowledge!
Topic archived. No new replies allowed.