Help with this problem
Jun 28, 2022 at 10:06am
and what is your current effort to code this? How far have you got? What issues are you having? Post your current code.
Jun 28, 2022 at 10:24am
Based upon code from
https://cplusplus.com/forum/lounge/284112/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <cctype>
#include <ranges>
namespace rngs = std::ranges;
auto get_words(std::istream& ifs) {
static constexpr char split { '-' };
std::vector<std::string> words;
for (std::string wrd; ifs >> wrd; ) {
std::string w;
rngs::copy_if(wrd, std::back_inserter(w), [](unsigned char ch) {return ch == split || std::isalpha(ch); });
for (const auto& word : rngs::split_view(w, split))
if (word.begin() != word.end())
words.emplace_back(word.begin(), word.end());
}
return words;
}
int main() {
std::ifstream ifs("test.txt");
if (!ifs)
return (std::cout << "Cannot open file\n"), 1;
constexpr size_t NoLet { 26 };
unsigned cnt[NoLet] {};
std::cout << "Starting letter count:\n";
for (const auto& w : get_words(ifs))
++cnt[static_cast<char>(std::toupper(static_cast<unsigned char>(w[0]))) - 'A'];
for (size_t l {}; l < NoLet; ++l)
if (cnt[l])
std::cout << static_cast<char>('A' + l) << ' ' << cnt[l] << '\n';
}
|
Starting letter count:
A 4
B 2
D 1
G 2
I 1
M 2
O 1
R 1
S 1
T 6
W 2
|
Jun 28, 2022 at 10:32am
where i can post the code? |
Here. Use code tags when posting code:
[code]
formatted code goes here
[/code]
|
Jun 28, 2022 at 11:55am
... but can you understand and explain it?
If that was for a homework exercise, then...
Topic archived. No new replies allowed.