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

C语言使用getchar()统计字符:输入5个数字却输出10的问题咨询

getchar()统计字符数结果为10而非5的原因

代码示例

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

int main()
{
    int num=0,ch='9';

    while((ch=getchar())!=EOF){
        ++num;
    }
    printf("\n%d",num);
}

/* this is a program to count no of characters entered using getchar(). 

输入内容

1
2
3
4
5

原因解析

  • getchar()会读取输入流里所有字符,包括你按下回车键生成的换行符(\n)。
  • 你输入的每个数字后面都跟着一个换行符:输入1回车,实际输入了'1'和'\n';2到5同理,总共是5个数字字符 + 5个换行符,加起来正好10个字符。
  • 程序没有做字符过滤,把所有输入的字符都计入统计,所以结果是10,而非你预期的仅数字字符数量5。

修正方案(可选)

如果只想统计数字字符,可以在循环里增加判断逻辑:

while((ch=getchar())!=EOF){
    // 仅当输入是0-9的数字时才计数
    if (ch >= '0' && ch <= '9') {
        ++num;
    }
}

内容的提问来源于stack exchange,提问作者Devesh from India

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:34:54