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];.
#include<iostream>
#include<string>
usingnamespace 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!
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
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!