我正在尝试做什么
我正在尝试计算字符串中的字符数。我尝试将字符串保存在数组 CH[100]
中,然后启动 switch-statement
来查找字符 Q
的重复次数...
代码
114.c
#include <stdio.h>
#define SIZE 100
int main(int argc, char* argv[])
{
char* CH[SIZE];
int alpha[26] = { 0 };
unsigned int i = 0;
printf("name\n");
scanf("%s", CH);
while(i < SIZE){
if(CH[i] != '\0')
{
switch(CH[i])
{
case 'a':
case 'A': ++alpha[0]; break;
case 'b':
case 'B': ++alpha[1]; break;
case 'c':
case 'C': ++alpha[1]; break;
. . .
. . .
. . .
case 'y':
case 'Y': ++alpha[24]; break;
case 'z':
case 'Z': ++alpha[25]; break;
}//end switch
}else{ break;}
++i;
}//end while
for(int j = 65; j < 91; ++j)
{
if(alpha[j- 65] != 0)
printf("%s\t - %d times\n",(char) j,alpha[j- 65]);
}
}
编译和执行:
[ar.lnx@host Documents] $ gcc 114.c -o x
[ar.lnx@host Documents] $ ./x
donner le nom
anas
Segmentation fault (core dumped)
[ar.lnx@host Documents] $
我不明白问题出在哪里,有人可以帮我看看这里发生了什么
最佳答案
那么,将 printf
中的 %s
更改为 %c
。
做
printf("%c\t - %d times\n",(char) j,alpha[j- 65]);
而不是
printf("%s\t - %d times\n",(char) j,alpha[j- 65]);
您更正后的代码是
#include <stdio.h>
#define SIZE 100
int main(int argc, char* argv[])
{
char CH[SIZE];
int alpha[26] = { 0 };
unsigned int i = 0;
printf("name\n");
scanf("%s", CH);
while(i < SIZE){
if(CH[i] != '\0')
{
switch(CH[i])
{
case 'a':
case 'A': ++alpha[0]; break;
case 'b':
case 'B': ++alpha[1]; break;
case 'c':
case 'C': ++alpha[1]; break;
case 'y':
case 'Y': ++alpha[24]; break;
case 'z':
case 'Z': ++alpha[25]; break;
}//end switch
}else{ break;}
++i;
}//end while
int j;
for( j = 65; j < 91; ++j)
{
if(alpha[j- 65] != 0)
printf("%c\t - %d times\n",(char) j,alpha[j- 65]);
}
}
如果您对 %c
和 %s
之间的差异有疑问,请检查 this .
关于c - 使用 scanf() 和 switch 语句计算字符串中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35458701/