我想编写一个程序,可以获得一个句子中每个不同字符的数量。但是当我使用gcc编译我的代码时,它会显示如下错误: 错误::在'['标记之前预期的非限定标识。并且这些错误发生在以下行中:
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
if(*(S.ch)==CountMachine[j].ch)
.....
(where I use CountMachine[]).
这是我的完整代码:
CountChar.h:
typedef struct
{
char ch;
int count=0;
}CountMachine[50];
typedef struct
{
char *ch;
int length;
}HString;
CountChar.cpp(但我使用C的语法)
void CountChar(HString S)
{
int cnt=0;
for(int i=0;i<S.length;i++)
{
if(i==0)
{
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
cnt++;
S.ch++;
}
else
{
for(int j=0;j<cnt;j++)
{
if(*(S.ch)==CountMachine[j].ch)
{
CountMachine[j].count++;
S.ch++;
break;
}
if(j==cnt-1)
{
CountMachine[cnt].ch=*(S.ch);
CountMachine[cnt].count++;
cnt++;
S.ch++;
}
}
}
}
printf("There are %d different characters.\n",cnt-1);
for(int m=0;m<cnt-1;m++)
{
printf("the number of character %c is %d",CountMachine[m].ch,CountMachine[m].count);
}
}
答案 0 :(得分:0)
你有一个非常奇特的类型别名,它声明了一个CountMachine
类型,而不是一个包含50个未命名结构的数组的变量。
typedef struct
{
char ch;
int count=0;
}CountMachine[50];
// CountMachine is a type (array 50 of unnamed struct)
// step-by step declaration is much more clear:
struct machine
{
char ch;
int count=0;
};
typedef struct machine machine_t;
machine_t machines[50];
// machines is a variable that holds an array of 50 machine_t
答案 1 :(得分:0)
您将CountMachine
声明为包含50个CountChar.h
中包含字符和整数的结构的类型,然后在CountChar.cpp
中解析该类型。
您无法处理某个类型中的特定项,您需要创建CountMachine
类型的变量,或从标题中typedef
的声明中删除关键字CountMachine
。 / p>