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

关于getchar()读取printf输出内容的C语言问题咨询

问题分析与解决

首先纠正你的误解:getchar()不会读取printf()的输出内容,问题出在输入流的处理逻辑上:

  • 当你输入1并按下回车时,输入流里实际包含两个字符:'1'和换行符'\n'。循环每次调用getchar()会读取一个字符,这两个字符都不是EOF,所以两次循环都会把c设为1,自然打印两次1。
  • 按下Ctrl-D后,输入流被标记为EOF,后续所有getchar()调用都会返回EOF,所以剩余的循环迭代中c始终为0,会持续打印。

解决方法

方案1:读取字符后清空输入缓冲区的换行符

如果你希望每次输入一个有效字符后,跳过后续的换行符(避免被getchar()读取),可以在读取字符后添加清空缓冲区的逻辑:

#include <stdio.h>

int main() {
  int c;
  for (int i = 0; i < 10; i++) {
    c = (getchar() != EOF);
    printf("%d\n", c);
    
    // 清空输入缓冲区中剩余的字符,直到遇到换行或EOF
    if (c) {
      int temp;
      while ((temp = getchar()) != '\n' && temp != EOF);
    }
  }
  printf("As we can see, the value of c is either 0 or 1 (as claimed in the book)\n");
  return 0;
}

方案2:遇到EOF直接终止循环

如果你想在输入EOF后立刻停止循环,避免持续打印0,可以修改循环的终止条件:

#include <stdio.h>

int main() {
  int c;
  int i = 0;
  while (i < 10) {
    c = getchar();
    if (c == EOF) {
      break; // 遇到EOF直接退出循环
    }
    printf("1\n");
    
    // 清空后续的换行符
    int temp;
    while ((temp = getchar()) != '\n' && temp != EOF);
    i++;
  }
  printf("As we can see, the value of c is either 0 or 1 (as claimed in the book)\n");
  return 0;
}

方案3:跳过所有空白字符(包括空格、换行)

如果需要忽略输入中的空白字符,只处理有效输入字符,可以用如下逻辑:

#include <stdio.h>

int main() {
  int c;
  for (int i = 0; i < 10; i++) {
    // 跳过空白字符,直到读到有效字符或EOF
    do {
      c = getchar();
    } while (c != EOF && (c == ' ' || c == '\n' || c == '\t'));
    
    int result = (c != EOF);
    printf("%d\n", result);
    
    // 如果读到有效字符,跳过后续的换行
    if (result) {
      int temp;
      while ((temp = getchar()) != '\n' && temp != EOF);
    }
  }
  printf("As we can see, the value of c is either 0 or 1 (as claimed in the book)\n");
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:49:49