计算字符串C ++中'0'-'9'的出现次数

用户206904

我正在尝试制作一个程序,该程序将要求用户仅输入一个数字字符串。一旦进入该程序,该程序必须计算每个数字的出现次数并将其填入表格中。例如:用户输入“01230012340067080”程序应该返回:7 2 2 2 1 0 1 1 1 0

0 : 7 发生 1 : 2 2 : 2 3 : 2 4 : 1 5 : 0 6 : 1 7 : 1 8 : 1 9 : 0

这是我的代码,它没有返回所需的结果

#include<iostream>
#include<string.h>
using namespace std;
const int MAX_CH = 64;


bool is_number(char chaine[MAX_CH])
{
    int l,i;
    i=0;
    l=strlen(chaine);
    for (i=0; i<l; i++)
    {
        if (chaine[i]<'0' || chaine[i]>'9')
        {
            return false;
        }
    }
    return true;
}


void tableau_occurence(char chaine_a_tester[MAX_CH], int taboccurence[10])
{
  //int i;
  //int j,c;
  //j=0;
  //i=0;
  for (int i=0; i<10; i++)
  {
      for (char j='0';j<'10';j ++)
      {
          if (chaine_a_tester[i] == j)
          {
           taboccurence[i]=taboccurence[i]+1;
          }

      }

   }
}

void tab_ini(int tableau[10])
{
    int i;
    i=0;
    for (i=0; i<10; i++)
    {
        tableau[i]=0;
    }
}
void affiche_tab(int tableau[10])
{
    int i;
    i=0;
    for (i=0; i<10; i++)
    {
        cout<<tableau[i]<<"     ";
    }
    cout<<endl;
}

void affiche_after(int tableau[10])
{
    int i;
    i=0;
    for (i=0; i<10; i++)
    {
        cout<<"nombre de "<< i<<" est : "<<tableau[i]<<endl;
    }

}




int main(void)
{
    char unechaine[MAX_CH];
    int tab[10];
    tab_ini(tab);
    affiche_tab(tab);
    cout<<"entrer votre chaine numerique  "<<endl;
    cin>>unechaine;
    while (is_number(unechaine)!= 1)
    {
        cout<<"numbers only!!"<<endl;
        cin>>unechaine;
    }
    tableau_occurence(unechaine,tab);
    affiche_after(tab);

    return 0;
}
皮特·贝克尔

要计算每个数字出现的次数,请将字符转换为相应的数字并将其用作数组的索引。这是一个草图:

int digit_counts[10];

while (*str) {
    if ('0' <= *str && *str <= '9')
        digit_counts[*str - '0']++;
    ++str;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章