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

Function main

Exercises/NoModules/Chapter 07/Soln7_08B.cpp:12–81  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10#include <vector>
11
12int main()
13{
14 // Ignore small words
15 const size_t small_word_bound{ 3 }; // Set to 0 to not ignore small words at all
16 const double near_tautology_ratio_bound{ 0.7 }; // Set to 1 to always require 100% of the words to begin with the same letter
17
18 std::string text; // The text to be checked
19 std::cout << "Enter some text terminated by *:\n";
20 std::getline(std::cin, text, '*');
21
22 std::vector<std::string> words;
23 for (size_t i {}; i < text.length(); )
24 {
25 // Skip spaces until we find the start of a word...
26 while (i < text.length() && !std::isalpha(text[i])) ++i;
27
28 const size_t start{ i };
29
30 // Search for the end of the word...
31 while (i < text.length() && std::isalpha(text[i])) ++i;
32
33 if (i > start)
34 {
35 words.push_back(text.substr(start, i - start));
36 }
37 }
38
39 // Only search for tautograms where words start with Latin letters A - Z
40 size_t counts[26] {}; // All counts are initialized to 0
41 size_t long_word_count{};
42
43 for (auto& word : words)
44 {
45 if (word.length() > small_word_bound)
46 {
47 ++long_word_count;
48 const auto start_letter{ std::toupper(word[0]) };
49 if (start_letter >= 'A' && start_letter <= 'Z')
50 {
51 ++counts[start_letter - 'A'];
52 }
53 }
54 }
55
56 // Look for the most common start letter
57 size_t most_common_index{ 0 };
58 for (size_t i{ 1 }; i < std::size(counts); ++i)
59 {
60 if (counts[i] > counts[most_common_index])
61 {
62 most_common_index = i;
63 }
64 }
65
66 const auto most_common_start_letter{ static_cast<char>('A' + most_common_index) };
67
68 if (counts[most_common_index] == words.size())
69 {

Callers

nothing calls this directly

Calls 2

push_backMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected