首页 > 解决方案 > I'm finding the frequency of each letter, although it always returns 0 for all the letters

问题描述

int main (){
    char string[100];
    int c=0,count[26]={0},x;
    gets(string);
    while(string[c]!='\0'){
        if (string[c] >= 'a' && string[c] <= 'z') {
            x = string[c] - 'a';
            count[x]++;
        }
        c++;
    }

    for (c = 0; c < 26; c++){
        printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
    }
    return 0;
}

Firstly, it gives me this error about get: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration] gets(string); And I don't know why doesn't work, although it makes sense.

标签: c

解决方案


gets()使用是有风险的。它会遭受缓冲区溢出,因为 gets() 不进行任何数组绑定测试。gets()继续阅读,直到看到换行符。

尝试scanf("%99[^\n]", string);代替您的代码gets(string);

试试这个修改后的代码。这将起作用:-

#include <stdio.h>
int main (){
    char string[100];
    int c=0,count[26]={0},x;
    scanf("%99[^\n]", string);
    while(string[c]!='\0'){
        if (string[c] >= 'a' && string[c] <= 'z') {
            x = string[c] - 'a';
            count[x]++;
        }
        c++;
    }

    for (c = 0; c < 26; c++){
        printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
    }
    return 0;
}

另一种解决方案是使用fgets().

您可以使用fgets(string,100, stdin);而不是 gets(string);.

修改后的代码将是:-

#include <stdio.h>
int main (){
    char string[100];
    int c=0,count[26]={0},x;
    fgets(string,100, stdin);  // 100 is the Max Limit of array
    while(string[c]!='\0'){
        if (string[c] >= 'a' && string[c] <= 'z') {
            x = string[c] - 'a';
            count[x]++;
        }
        c++;
    }

    for (c = 0; c < 26; c++){
        printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
    }
    return 0;
}

推荐阅读