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

Function main

Exercises/NoModules/Chapter 07/Soln7_06.cpp:14–57  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12#include <vector>
13
14int main()
15{
16 std::string text; // The text to be searched
17 std::string letters;
18 std::cout << "Enter some text terminated by *:\n";
19 std::getline(std::cin, text, '*');
20 std::cout << "\nEnter the starting letters for the words you want to find: ";
21 std::cin >> letters;
22
23 const std::string separators {" ,;:.\"!?'\n"}; // Word delimiters
24 std::vector<std::string> words; // Words found
25 const size_t perline {5}; // Words output per line
26 size_t count {}; // Number of words found
27 for (auto ch : letters)
28 {
29 size_t start {text.find_first_not_of(separators)}; // First word start index
30 size_t max_length {}; // Maximum word length
31 while (start != std::string::npos) // Find the words
32 {
33 auto end{ text.find_first_of(separators, start + 1) }; // Find end of word
34 if (end == std::string::npos) // Found a separator?
35 end = text.length(); // No, so set to last + 1
36 auto word{ text.substr(start, end - start) }; // Record the word
37 if (std::toupper(word[0]) == std::toupper(ch)) // If it begins with the current letter...
38 {
39 words.push_back(word); // ...save the word
40 if (max_length < word.length()) max_length = word.length();
41 }
42
43 start = text.find_first_not_of(separators, end + 1); // Find 1st character of next word
44 }
45 // List words for current letter
46 std::cout << "\nWords beginning with '" << ch << "' are:\n";
47 for (auto& word : words)
48 {
49 std::cout << std::format("{:<{}}", word, max_length + 2);
50 if (++count % perline) continue;
51 std::cout << std::endl;
52 }
53 std::cout << std::endl;
54 words.clear();
55 count = 0;
56 }
57}

Callers

nothing calls this directly

Calls 2

push_backMethod · 0.45
clearMethod · 0.45

Tested by

no test coverage detected