C++ vector Storing student names and grades

Description

C++ vector Storing student names and grades

#include <iostream>
#include <iomanip>
#include <cctype>
#include <vector>
#include <string>
using std::string;

int main(){//  w  ww.j  av  a  2 s  . c  o  m
  std::vector<string> names;
  std::vector<double> grades;
  double average_grade {};
  char answer {};

  string name;
  int max_length {};
  double grade {};

  while(true){
    std::cout << "Enter a student's name: ";
    std::cin >> name;

    names.push_back(name);

    if (max_length < name.length())
       max_length = name.length();

    std::cout << "Enter " << name << "\'s grade: ";
    std::cin >> grade;

    grades.push_back(grade);

    average_grade += grade;

    std::cout << "Do you wish to enter another student's details (y/n): ";
    std::cin >> answer;

    if (std::toupper(answer) == 'N')
       break;
  }

  average_grade /= grades.size();

  std::cout << "\nThe class average for " << names.size() << " students is "
    << std::fixed << std::setprecision(2) << average_grade << std::endl;


  const int perline {3};

  for (int i {}; i < names.size(); ++i){
    std::cout << "  " << std::left << std::setw(max_length) << names[i]
              << std::right << std::setw(6) << std::setprecision(2) << grades[i];
    if ((i + 1) % perline) continue;
    std::cout << std::endl;
  }
  std::cout << std::endl;
}



PreviousNext

Related