can anyone tell why the first and last name option appears at the same time when 2nd student name is entered

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
struct student
{
char firstName[20];
char lastName[20];
char rollNo[20];
double quiz1;
double quiz2;

};
int main()
{
student student1[2];
for(int i=0; i<2; i++)
{
cout<<"please enter the first name of student "<<i+1<<endl;
cin.getline(student1[i].firstName,20,'\n');

cout<<"please enter the last name of student "<<i+1<<endl;
cin.getline(student1[i].lastName,20,'\n');

cout<<"please enter the roll number of student "<<i+1<<endl;
cin.getline(student1[i].rollNo,20,'\n');

cout<<"please enter the quiz 1 marks of student "<<i+1<<endl;
cin>>student1[i].quiz1;

cout<<"please enter the quiz 2 marks of student "<<i+1<<endl;
cin>>student1[i].quiz2;


}

for(int j=0; j<2; j++)
{
cout<<"First Name of student "<<j+1<<": "<<student1[j].firstName<<endl;
cout<<"Last Name of student "<<j+1<<": "<<student1[j].lastName<<endl;
cout<<"Roll number of student "<<j+1<<": "<<student1[j].rollNo<<endl;
cout<<"Quiz 1 marks of student "<<j+1<<": "<<student1[j].quiz1<<endl;
cout<<"Quiz 2 marks of student "<<j+1<<": "<<student1[j].quiz2<<endl;
}





return 0;
}
how can i have first name and last name seperated? your help will be appreciated .. thanks
Last edited on
add cin.ignore() after last cin in first for statement like this:

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
33
int main()
{
   student student1[2];
   for(int i=0; i<2; i++)
   {
      cout<<"please enter the first name of student "<<i+1<<endl;
      cin.getline(student1[i].firstName,20, '\n');

      cout<<"please enter the last name of student "<<i+1<<endl;
      cin.getline(student1[i].lastName,20,'\n');

      cout<<"please enter the roll number of student "<<i+1<<endl;
      cin.getline(student1[i].rollNo,20,'\n');

      cout<<"please enter the quiz 1 marks of student "<<i+1<<endl;
      cin>>student1[i].quiz1;

      cout<<"please enter the quiz 2 marks of student "<<i+1<<endl;
      cin>>student1[i].quiz2;
      cin.ignore();
   }

   for(int j=0; j<2; j++)
   {
      cout<<"First Name of student "<<j+1<<": "<<student1[j].firstName<<endl;
      cout<<"Last Name of student "<<j+1<<": "<<student1[j].lastName<<endl;
      cout<<"Roll number of student "<<j+1<<": "<<student1[j].rollNo<<endl;
      cout<<"Quiz 1 marks of student "<<j+1<<": "<<student1[j].quiz1<<endl;
      cout<<"Quiz 2 marks of student "<<j+1<<": "<<student1[j].quiz2<<endl;
   }

   return 0;
}
Thank u so much brother.. ur help is highly appreciated.. thanks once again.. :)
You can also use fflush(stdin); to clear the buffer in place of cin.ignore();
fflush(stdin); invokes undefined behavior
thank u atyab and cubbi :)
Topic archived. No new replies allowed.