M
M
Matef2020-11-16 23:47:43
C++ / C#
Matef, 2020-11-16 23:47:43

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

2 answer(s)
G
galaxy, 2020-11-17
@Matef

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()

R
Roman, 2020-11-17
@myjcom

Without spaces

Конец ввода это комбинация клавиш Ctrl + D в Linux и Ctrl + Z в Windows
#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";
  }
}


with spaces

#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";
  }
}


It is still necessary to figure out the output of Russian letters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question