C++ basically mandates Latin-1 encoding in the Standard, but it is always better to avoid magic numbers anyway. Use
'A'
instead of 65. (A
char
is an integer type, so you can use it directly.)
Using a short array to hold the letters is a good answer.
Zapshe should have suggested better variable names, like
histogram
(or something similar) for the letter lookup.
His code also has an overflow error: before accessing the array on line 12 he should have verified that both the array and the input is within bounds:
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
int histogram[ 'Z' - 'A' + 1 ] = { 0 }; // correctly-sized array
int word_count;
char last_c = ' ';
for (char c : input)
{
if (std::isalpha( c )) // no out-of-bounds accesses
{
histogram[ std::toupper( c ) - 'A' ] += 1;
}
else if (std::isspace( c ) && !std::isspace( last_c ))
{
word_count += 1;
}
last_c = c;
}
if (!std::isspace( last_c ))
{
word_count += 1;
}
|
And don’t forget to
#include <cctype>
for those fancy character handling routines.
If I were doing this, I would be inclined to use a
std::map <char, std::size_t>
for my histogram — all that character arithmetic would be obviated, and there would be no need to check against zero values in the histogram.
Here’s something that is almost guaranteed to get you a fail-for-cheating if you turn it in, but nevertheless demonstrates modern C++ for you:
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
|
#include <cctype>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
int main()
{
// These are our letter histogram and word count
std::map <char, std::size_t> histogram;
std::size_t word_count = 0;
// Get the input string to break into words
std::string s;
std::cout << "s? ";
getline( std::cin, s );
// Break the string into words and histogram the letters, case-insensitively
std::istringstream ss( s );
while (ss >> s)
{
word_count += 1;
for (char c : s)
if (std::isalpha( c ))
histogram[ std::toupper( c ) ] += 1;
}
// Display the word count...
std::cout << word_count << ((word_count == 1) ? " word\n" : " words\n");
// ...and the letter histogram
for (auto [c, n] : histogram)
std::cout << n << " " << c << ((n == 1) ? "\n" : "'s\n");
}
|
Tada!
s? The quick red fox jumps over the lazy brown dog.
10 words
1 A
1 B
1 C
2 D's
4 E's
1 F
1 G
2 H's
1 I
1 J
1 K
1 L
1 M
1 N
4 O's
1 P
1 Q
3 R's
1 S
2 T's
2 U's
1 V
1 W
1 X
1 Y
1 Z |
Hope this helps.