The problem is that the program incorrectly counts the number of consonants in general. Maybe the problem is that the compiler does not understand Russian?

#include <iostream> #include <string> using namespace std; int consonantsNumber(const string &str) { int result = 0; string consonants = "бвгджзйклмнпрстфхцчшщ"; for (int i = 0; i < str.size(); i++) for (int j = 0; j < consonants.size(); j++) if ( tolower(str[i]) == consonants[j] ) { result++; } return result; } int main() { string s; getline(cin, s); cout << consonantsNumber(s); return 0; } 
  • one
    Of course, the compiler does not understand. More truly, not the compiler. And your program. 1) In what encoding do you write the letters in the program? 2) in what encoding enter the string in the console? Do you think they match? Are they single-byte at least? - If single-byte, then everything is treated simply by adding a couple of commands, but if there is unicode ... You will need to convert something else before comparing ... - Vladimir
  • Well, I understood, but can somehow without a switch and without a heap if else find the number of repetitions of each letter? - Melliodas Nov.
  • Well, you can still use functions from the string type find_first_of() , etc. - they are able to search for a symbol from the provided string (i.e. it can feed your consonants ). And you can use an associative array ( map ) to keep statistics on each character (letter) - again, in order to get rid of conditions. But I am not sure that this will be clearer than with if/switch . And faster, too, is unlikely to become. - Vladimir
  • Or you can use functions from C, such as strpbrk . Even a similar example is: cplusplus.com/reference/cstring/strpbrk (about vowels). - Vladimir

1 answer 1

I think you should use std :: map to solve your problem.

 #include <string> #include <iostream> #include <map> int main() { setlocale(LC_ALL, "Russian"); std::string cs = "бвгджзйклмнпрстфхцчшщ"; std::map<char, int> consonants; for (auto ch : cs) consonants.emplace(ch, 0); std::string entr; std::getline(std::cin, entr); for (auto ch : entr) if (consonants.find(ch) != consonants.end()) consonants.find(ch)->second++; for (auto consonant : consonants) std::cout << "Кол-во буквы " << consonant.first << " в тексте: " << consonant.second << std::endl; return 0; }