Function to count all characters in a string - C++

c++

Solution

You're doing some kind of weird double loop. Instead, iterate over the string in a single loop and count it in the right group :

for (int i = 0; i < input.length(); i++) {
    char c = input[i];
    if (c < 'A' || c > 'Z') continue;
    countLetters[c-'A'] += 1;
}

Problem

I want to write a functioin in C++, which counts all characters in a string.# I have a string called input, in which the user of the program can enter a sentence, the letters that are important I stored in a string alphabet like this: ``` string alphabet {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; ``` and a vector that is used to store the frequency of occurrence of the letters, e.g. A is located on place 0, B on place 0, and so on. ``` vector<long> letterCount (26); ``` I have written the function like I think it should work, and it seems that it is able to figure out the occurences of the characters but after that this figure is multiplied by the place of the letter in the alphabet. Here is the function: ``` long countLetters(int& p) { for(int i = 0; i < alphabet.size(); ++i) { for(long j = 0; j < count(input.begin(), input.end(), alphabet.at(i)) { countLetters.at(i)++; } } return letterCount.at(p); } ``` For example, if the input is "HELLO" the programs puts out: ``` E : 5 H : 8 L : 24 O : 15 ``` So you see, for example the letter 'L' is contained two times in the string, but the result for 'L' is 24, because 'L' is at place 12 in the alphabet. Please help, if you realize what my problem is. EDIT: I've found a way that works, at least partially: ``` long countLetters(int& p) { for(size_t i = 0; i < input.length(); ++i) { for(size_t j = 0; j < alphabet.length(); ++j) { letterCount.at(j) = count(input.begin(), input.end(), alphabet.at(j)); } } return letterCount.at(p); } ``` But when entering two or more words the function only figures out the letter-occurences in the first word. How do I analyze more words? EDIT: before I had `cin >> input` but `getline(cin, input);` is right.

Original source