how cin.getline works

I need assistance wit an assignment I was given. I cant get the program to print out the first and last word at once. thanks

#include <iostream>
#include <cstring>
#include <string>
int main()
{
using namespace std;


char lastname [20];
char firstname [20];
char major[20];
char major2[20];
int age;
float gpa;


cout<<" STUDENT #1 \n"<<endl;
cout<<"What is your major?"<<endl;
cin.getline(major, 20);
cout<<"What is your first name?"<<endl;
cin>> firstname;
cout<<"What is your last name?"<<endl;
cin>> lastname;
cout<<"How old are you?"<<endl;
cin>> age;
cout<<"What is your GPA?"<<endl;
cin>> gpa;
if(gpa <2 )
{ cout<<"INVALID!"<<endl;
cout<<" Enter GPA, where GPA cannot be less than 2 or greater than 4";
cin>> gpa;}

if(gpa >4 )
{ cout<<"INVALID!"<<endl;
cout<<" Enter GPA, where GPA cannot be less than 2 or greater than 4\n";
cin>> gpa;}
cout<<"\n";

cout<<"Hello "<<firstname<<" "<<lastname<<"\n"<<endl;
cout<<"You are "<< age<<" years of age"<<" and your major is "<<major<<"\n"<<endl;
cout<<"Your present GPA is:"<<gpa<<"\n"<<endl;
cout<<"\n"<<endl;



cout<<" STUDENT #2 \n"<<endl;
cout<<"What is your major?"<<endl;
cin.getline(major2, 20);
cout<<"What is your first name?"<<endl;
cin>> firstname;
cout<<"What is your last name?"<<endl;
cin>> lastname;
cout<<"How old are you?"<<endl;
cin>> age;
cout<<"What is your GPA?"<<endl;
cin>> gpa;
if(gpa <2 )
{ cout<<"INVALID!"<<endl;
cout<<" Enter GPA, where GPA cannot be less than 2 or greater than 4";
cin>> gpa;}

if(gpa >4 )
{ cout<<"INVALID!"<<endl;
cout<<" Enter GPA, where GPA cannot be less than 2 or greater than 4\n";
cin>> gpa;}
cout<<"\n"<<endl;

cout<<"Hello "<<firstname<<" "<<lastname<<"\n"<<endl;
cout<<"You are "<< age<<" years of age"<<" and your major is "<<major2<<"\n"<<endl;
cout<<"Your present GPA is:"<<gpa<<"\n"<<endl;
cout<<"\n";




system("pause");
return 0;
}
Add these two lines of code before getting data from student #2:

1
2
3
4
   char ch;
   cin.get(ch);

   cout << " STUDENT #2\n" << endl;


The cin.get(ch) will eat up the newline that cin >> gpa; left in the stream. With your original code, cin.getline(major2, 20) reads that newline, discards it, and returns. That's why you don't get a chance to enter the major.
Last edited on
Topic archived. No new replies allowed.