What's wrong with this? (Counting number of occurences of each letter in a sentence)

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        string sentence;
	
	getline(cin,sentence);
	
	int length=sentence.length();
	int count[length];
	
	for(int i=0; i<length;i++)
		for(char j=97; j<122;j++)
		{
			char let=sentence.at(i);
			if(let==j)
				count[i]++;
		}
	for(int i=0; i<length;i++)
		cout<<sentence[i]<<" "<<count[i];
First, you really shouldn't use hard-coded character values, instead prefer the actual char values. Also, your count array is counting the wrong things, as well as being an illegal declaration and not setting its values. Try something like this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <iostream>

int main() {
    std::string sentence;
    std::getline(std::cin, sentence);
    
    unsigned int count[26] = {0}; // number of letters in the alphabet
    
    for (unsigned int i = 0; i < sentence.length(); ++i) {
        // If the letter is lower case alphabetical
        // (you can change for uppercase if you want, too)
        if (std::isalpha(sentence[i]) && std::islower(sentence[i]))
            ++count[sentence[i] - 'a'];
    }
    
    for (char c = 0; c < 26; ++c) {
        if (count[c] != 0)
            std::cout << static_cast<char>(c + 'a') << ": " << count[c] << '\n';
    }
        
    return 0;
}

http://coliru.stacked-crooked.com/a/b1e16d05f01088ca
Last edited on
thanks dude! It works now
Topic archived. No new replies allowed.