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

Function main

Examples/NoModules/Chapter 07/Ex7_03.cpp:7–53  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5#include <vector> // For the vector container
6
7int main()
8{
9 std::vector<std::string> names; // Vector of names
10 std::string input_name; // Stores a name
11
12 for (;;) // Indefinite loop (stopped using break)
13 {
14 std::cout << "Enter a name followed by Enter (leave blank to stop): ";
15 std::getline(std::cin, input_name); // Read a name and...
16 if (input_name.empty()) break; // ...if it's not empty...
17 names.push_back(input_name); // ...add it to the vector
18 }
19
20 // Sort the names in ascending sequence
21 bool sorted {};
22 do
23 {
24 sorted = true; // remains true when names are sorted
25 for (size_t i {1}; i < names.size(); ++i)
26 {
27 if (names[i-1] > names[i])
28 { // Out of order - so swap names
29 names[i].swap(names[i-1]);
30 sorted = false;
31 }
32 }
33 } while (!sorted);
34
35 // Find the length of the longest name
36 size_t max_length{};
37 for (const auto& name : names)
38 if (max_length < name.length())
39 max_length = name.length();
40
41 // Output the sorted names 5 to a line
42 const size_t field_width{ max_length + 2 };
43 size_t count {};
44
45 std::cout << "In ascending sequence the names you entered are:\n";
46 for (const auto& name : names)
47 {
48 std::cout << std::format("{:>{}}", name, field_width); // Right-align + dynamic width
49 if (!(++count % 5)) std::cout << std::endl;
50 }
51
52 std::cout << std::endl;
53}

Callers

nothing calls this directly

Calls 4

emptyMethod · 0.45
push_backMethod · 0.45
sizeMethod · 0.45
swapMethod · 0.45

Tested by

no test coverage detected