0

I have looked around and can't seem to find an answer to this. I am new to C++ and am attempting to write a program for a class that asks the user for the first and last names of 4 students and their ages. The program will then display the input names and ages and also display the average of the ages.

The issue I am having is that the program allows for input of the first name and age but then skips over the remaining three name input fields and only allows for the remaining three ages to be input.

I apologize if this ends up being a dumb question but I really am at a loss. Any help will be greatly appreciated.

Here is the code I have thus far:

#include <iostream>
#include <string>
using namespace std;

int main()

{

  string studentname1;
  cout << "Please enter the first student's full name:" << endl;
  getline(cin, studentname1);

  int age1;
  cout << "Please enter the first student's age:" << endl;
  cin >> age1;

  string studentname2;
  cout << "Please enter the second student's full name:" << endl;
  getline(cin, studentname2);

  int age2;
  cout << "Please enter the second student's age:" << endl;
  cin >> age2;

  string studentname3;
  cout << "Please enter the third student's full name:" << endl;
  getline(cin, studentname2);

  int age3;
  cout << "Please enter the third student's age:" << endl;
  cin >> age3;

  string studentname4;
  cout << "Please enter the fourth student's full name:" << endl;
  getline(cin, studentname2);

  int age4;
  cout << "Please enter the fourth student's age:" << endl;
  cin >> age4;

  cout << "Hello from our group." << endl;
  cout << "NAME                         AGE" << endl;
  cout << studentname1 << "             " << age1 << endl;
  cout << studentname2 << "             " << age2 << endl;
  cout << studentname3 << "             " << age3 << endl;
  cout << studentname4 << "             " << age4 << endl;

  cout << "The average of all our ages is: " << (age1 + age2 + age3 + age4) / 4.00 << endl;

  return 0;

}
Astinog
  • 1,151
  • 3
  • 12
  • 35
  • possible duplicate of [using getline(cin, s) after cin](http://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin) – stefaanv Sep 07 '15 at 07:03

1 Answers1

1

Since the age variables are int, the cin >> age1; will leave the newline character in the input stream. When next you call getline(), you will get the remainder of that line - which is empty, and so on.

Also, you have a copy-paste bug in your code. getline(cint, studentname2); is run for students 2, 3 and 4.

You can either solve the problem by using getline() for all input:

string agestring;
getline(cin, agestring)
stringstream(agestring) >> age1;

or clear cin when you're done reading the age:

cin >> age1;
cin.ignore();
anorm
  • 2,255
  • 1
  • 19
  • 38