I run this program, as I'm trying to learn structures better, and it doesn't work. There are no error messages. Rather, it goes through the steps of asking for the name, me putting it in, then it asks for the age, i put it in. Instead of continuing on to the school lines, though, it immediately clears the screen and asks for the next name, back at the start of the loop. thanks in advance for any help
#include <iostream>
#include <string>
#include <cstdlib>
usingnamespace std;
int main()
{
struct personInfo
{
string name;
int age;
string school;
};
personInfo person[5];
for (int i=0;i<5;i++)
{
cout<<"Give me a name"<<endl;
getline(cin,person[i].name);
cout<<"How old is "<<person[i].name<<"?"<<endl;
cin>>person[i].age;
cout<<"What school does "<<person[i].name<<" go to?"<<endl;
getline(cin,person[i].school);
system("cls");
}
system ("cls");
cout<<"/t Name /t Age /t School"<<endl<<endl;
for (int i=0;i<5;i++)
{
cout<<"Person"<<i+1<<":/t"<<person[i].name<<"/t"<<person[i].age<<"/t"<<person[i].school<<endl;
}
}
The reason why it's not working is that cin >> person[i].age; on line 25 leaves a newline character in the input buffer, which getline eats on line 27 instead of waiting for more input.
Try replacing line 27 with
getline(cin >> ws, person[i].school); (and similarly on line 23)
and see if that helps. (What this does is eat all of the leading whitespace first so that getline doesn't accidentally grab a stray newline.)