Answer the question
In order to leave comments, you need to log in
Can't print how many identical characters a string contains?
The program should calculate how many identical characters a sentence contains in C ++
That's what I got, but it doesn't work if you put spaces and all the time you need to write how many characters the word contains, I tried to fix it with the strlen() function but it didn't help. Help tell me what I'm doing wrong please!?
The code:
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Введите кол-во символов строки: ";
cin >> num;
int arr[256] = {}; // массив счетчиков символов
char str[num]; // текст
cout << "Введите текст: "; //Просим пользователя ввести текст
cin >> str;
// инкрементируем счетчик символа с помощью цикла
for (int i = 0; i < num; ++i)
++arr[unsigned(str[i])];
// находим индекс максимального счетчика
int max = 0;
for (int i = 1; i < 256; ++i)
if (arr[max] < arr[i])
max = i;
cout << char(max) << " - " << arr[max] << endl; // выводим символ и сколько раз встречается
}
Answer the question
In order to leave comments, you need to log in
What a strange way to write in a hybrid of C and C++?
Write on pluses - use std::string.
cin >> reads up to first space, read via std::getline()
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> table;
char c = 0;
while(cin >> c) table[c]++;
for(auto [ch, cnt] : table)
{
cout << "symbol: '" << ch << "' count: " << cnt << "\n";
}
}
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<char, int> table;
string s;
getline(cin, s);
for(char c : s) table[c]++;
for(auto [ch, cnt] : table)
{
cout << "symbol: '" << ch << "' count: " << cnt << "\n";
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question