带有 scanf() 和 switch 语句的字符串中的字符数

number of chars in a string with scanf() and switch-statment

我想做什么

我正在尝试计算字符串中的字符数。我尝试将字符串保存在数组 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] != '[=10=]')
        {   
            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] $

我不明白这是什么问题,谁能帮我看看这是怎么回事

唯一的错误是在打印计数时将 %s 替换为 %c 即改变

printf("%s\t - %d times\n",(char) j,alpha[j- 65]);

printf("%c\t - %d times\n",(char) j,alpha[j- 65]);

好吧,在你的 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] != '[=12=]')
        {   
            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

问题出在您的 printf 格式上:

printf("%s\t - %d times\n",(char) j,alpha[j- 65]);

改成这样:

printf("%c\t - %d times\n",j,alpha[j- 65]);

char 转换是无害但不必要的。真正的问题是 %s 需要 %c.