MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / main

Function main

Exercises/NoModules/Chapter 07/Soln7_01.cpp:9–65  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7#include <string>
8
9int main()
10{
11 std::vector<std::string> names;
12 std::vector<double> grades;
13
14 size_t max_length {}; // Longest name length
15 double average_grade {}; // First accumulates the sum of the grades,
16 // to be divided by the number of grades later
17 // Data entry loop.
18 // This loop reads the name and grade for each student.
19 while (true)
20 {
21 std::cout << "Enter a student's name: ";
22 std::string name; // Stores a student name
23 std::getline(std::cin, name);
24
25 names.push_back(name);
26
27 if (max_length < name.length())
28 max_length = name.length();
29
30 std::cout << "Enter " << name << "\'s grade: ";
31 double grade {}; // Stores a student grade
32 std::cin >> grade;
33 grades.push_back(grade);
34
35 average_grade += grade;
36
37 std::cout << "Do you wish to enter another student's details (y/n): ";
38 char answer {};
39 std::cin >> answer;
40
41 // Ignore the line break that is still on the input stream after reading the y/n character
42 // Otherwise the next std::getline() always returns an empty line...
43 // (Note: we'll try to remember to add this annoyance as a hint in the next edition...)
44 std::cin.ignore();
45
46 if (std::toupper(answer) == 'N') break;
47 }
48
49 // Calculating the class average.
50 average_grade /= grades.size();
51
52 // Displaying the class average.
53 std::cout <<
54 std::format("\nThe class average for {} students is {:.2f}\n", names.size(), average_grade);
55
56 // Displaying the students' names and grades.
57 const size_t perline {3};
58 for (size_t i {}; i < names.size(); ++i)
59 {
60 std::cout << std::format("{:<{}} {:>4}\t", names[i], max_length, grades[i]);
61 if ((i + 1) % perline) continue;
62 std::cout << std::endl;
63 }
64 std::cout << std::endl;
65}

Callers

nothing calls this directly

Calls 2

push_backMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected