c - 使用 scanf() 和 switch 语句计算字符串中的字符数

标签 c arrays string switch-statement scanf

我正在尝试做什么

我正在尝试计算字符串中的字符数。我尝试将字符串保存在数组 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/

相关文章:

java - 将隐藏在字符串中的随机变化的数字设置为整数

c - 时间复杂度(Hackerrank 因超时 2 秒而终止)

c - 更快的测试和清除位

c - 初始化和访问struct中的char数组

C strcmp 将字符串与数组的前 x 个字符进行比较

java - 从左下角填充 gridview

c - #pragma inside #define

java - 给定类型的构造函数错误,无法应用

C++ 在句子中查找单词

javascript - 从正则表达式模式获取子字符串