You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计字符串字母频率全返回0且遇gets函数隐式声明警告的问题

Fixing Your C Program: Letter Frequency Count & gets Warning

Let's break down your issues one by one to get your program working correctly.

1. The gets Warning: Why It Matters & How to Fix It

That warning isn't just noise—gets was removed from the C standard in C11 because it's extremely unsafe. It doesn't check how much input you're typing, so if you enter more than 99 characters (since your string array is size 100), it'll overflow the buffer and cause undefined behavior (crashing, corrupting data, etc.).

The compiler suggests fgets for a good reason—it's the safe replacement. Here's how to swap it in:

fgets(string, sizeof(string), stdin);

But there's one catch: fgets includes the newline character (\n) at the end of the input string (when you press Enter). To avoid counting this as part of your string, add a quick check to remove it:

// Remove the trailing newline if present
size_t len = strlen(string);
if (len > 0 && string[len-1] == '\n') {
    string[len-1] = '\0';
}

(Note: You'll need to include <string.h> for strlen to work.)

2. Why All Letter Frequencies Are 0

There are a few common reasons for this:

  • You didn't enter any lowercase letters: Your code only counts characters between 'a' and 'z'. If you typed uppercase letters, numbers, symbols, or just pressed Enter without typing anything, all counts will stay 0.
  • gets failed to read your input: In some environments, gets might behave unexpectedly (especially if it's deprecated). Switching to fgets should resolve any input-reading issues that were causing your string to be empty or unprocessed.
  • Accidental input issues: Double-check that you're actually typing lowercase letters when testing the program—sometimes it's easy to have Caps Lock on without noticing!

Fixed Full Code

Here's the revised program with all fixes applied:

#include <stdio.h>
#include <string.h> // For strlen

int main (){
    char string[100];
    int c=0, count[26]={0}, x;

    printf("Enter a string: ");
    fgets(string, sizeof(string), stdin);

    // Remove trailing newline
    size_t len = strlen(string);
    if (len > 0 && string[len-1] == '\n') {
        string[len-1] = '\0';
    }

    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;
}

Test this with a string like "hello world!"—you'll see h:1, e:1, l:3, o:2, w:1, r:1, d:1 and all others 0, which is correct.

内容的提问来源于stack exchange,提问作者nadia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:50:49