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

C语言输入文件名后后续代码被忽略 无法输入待统计字符

问题原因

  • 调用scanf("%s", filename)读取文件名时,仅会读取连续的非空白字符,用户输入结束后按下的换行符\n会滞留在标准输入缓冲区中。
  • 后续执行scanf("%c", &inpt)时,%c格式符不会自动跳过前置空白字符,会直接读取到缓冲区中残留的换行符,因此程序不会等待用户手动输入,直接将换行符作为待统计的字符,最终统计结果为0。

修复方法

最简修复

将读取待统计字符的scanf语句修改为如下形式,%c前添加的空格会指示scanf自动跳过所有前置空白字符(包括残留的换行符):

scanf(" %c", &inpt);

通用修复(避免输入缓冲区残留问题)

在读取待统计字符前,主动清空输入缓冲区中的残留内容:

// 清空缓冲区直到遇到换行符
while (getchar() != '\n');
scanf("%c", &inpt);

更安全的输入方案

使用fgets逐行读取输入,从根源避免scanf的格式匹配遗留问题,同时补充原代码遗漏的文件关闭、fgetc返回值类型适配问题,完整调整后代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  char filename[128];
  printf("Name of the file: ");
  fgets(filename, sizeof(filename), stdin);
  // 去除fgets读取的末尾换行符
  filename[strcspn(filename, "\n")] = '\0';

  FILE * test = fopen(filename, "r");
  if (test == NULL) {
    printf("Error!!\n");
    exit(1);
  }

  char inpt_buf[8];
  printf("Character to be counted:\n");
  fgets(inpt_buf, sizeof(inpt_buf), stdin);
  char inpt = inpt_buf[0];

  int count = 0;
  // fgetc返回值为int,避免无符号char场景下EOF(-1)判断出错
  int search = fgetc(test);

  while(search != EOF) {
    if (search == inpt) count++;
    search = fgetc(test);
  }

  printf("The char occurs %d times in the file\n", count);
  
  fclose(test); // 补充文件关闭操作,避免资源泄漏
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:15:07