C++ 计数';0'-';9';以字符串C++;
我正在尝试制作一个程序,要求用户输入一个数字字符串。一旦输入,程序必须计算每个数字的出现次数 把这个填在表格里。 例如:用户输入“01230012340067080”程序应返回:7 2 2 1 0 1 1 0 发生0:7 发生1:2 发生2:2 发生3:2 发生4:1 发生5:0 发生6:1 发生7:1 发生8:1 发生9:0 这是我的代码,它不会返回期望的结果C++ 计数';0'-';9';以字符串C++;,c++,char,C++,Char,我正在尝试制作一个程序,要求用户输入一个数字字符串。一旦输入,程序必须计算每个数字的出现次数 把这个填在表格里。 例如:用户输入“01230012340067080”程序应返回:7 2 2 1 0 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 s
#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;
}
#包括
#包括
使用名称空间std;
常数int MAX_CH=64;
bool是字符数(字符链[MAX\u CH])
{
int l,i;
i=0;
l=strlen(链);
对于(i=0;i要计算每个数字的出现次数,请将字符转换为相应的数字,并将其用作数组的索引。以下是示意图:
int digit_counts[10];
while (*str) {
if ('0' <= *str && *str <= '9')
digit_counts[*str - '0']++;
++str;
}
int位_计数[10];
while(*str){
如果('0'有函数及其变体。为什么要使用
头?@Ron.string.h因为我使用了strlen。至于std:count,我尝试在不使用任何现有函数的情况下使用它。但是,如果使用适当的字符串和标准库函数,整个程序可以容纳11行或更少的代码。是的,我知道,但正如我所说的,我正在尝试o编写函数,避免使用现有函数。'10'
不是一个字符。工作起来很有魅力!谢谢!