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

Function main

Exercises/NoModules/Chapter 07/Soln7_02.cpp:7–59  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5#include <vector>
6
7int main()
8{
9 std::string text; // The text to be searched
10 std::cout << "Enter some text terminated by *:\n";
11 std::getline(std::cin, text, '*');
12
13 const std::string separators {" ,;:.\"!?'\n"}; // Word delimiters
14 std::vector<std::string> words; // Words found
15 std::vector<size_t> counts; // Words counts (same order as words)
16
17 size_t start {text.find_first_not_of(separators)}; // First word start index
18 while (start != std::string::npos) // Find the words
19 {
20 size_t end {text.find_first_of(separators, start + 1)}; // Find end of word
21 if (end == std::string::npos) // Found a separator?
22 end = text.length(); // No, so set to last + 1
23 std::string word{ text.substr(start, end - start) }; // Record the word
24
25 // Check for word already in vector
26 bool is_in {false}; // true when word has been found before
27 for (int i {}; i < words.size(); ++i)
28 {
29 if (words[i] == word)
30 {
31 ++counts[i];
32 is_in = true;
33 break;
34 }
35 }
36 if (!is_in) // If it's a new word...
37 {
38 words.push_back(word); // ...store the word...
39 counts.push_back(1); // ...and record the count
40 }
41 start = text.find_first_not_of(separators, end + 1); // Find 1st character of next word
42 }
43
44 // Find maximum word length
45 size_t max_length {};
46 for (auto& word : words)
47 if (max_length < word.length()) max_length = word.length();
48
49 std::cout << "Your string contains the following " << words.size() << " words and counts:\n";
50 size_t count {}; // Numbers of words output
51 const size_t perline {3}; // Number per line
52 for (size_t i {}; i < words.size(); ++i)
53 {
54 std::cout << std::format("{:<{}}{:>4} ", words[i], max_length, counts[i]);
55 if (!(++count % perline))
56 std::cout << std::endl;
57 }
58 std::cout << std::endl;
59}

Callers

nothing calls this directly

Calls 2

sizeMethod · 0.45
push_backMethod · 0.45

Tested by

no test coverage detected