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

我的C语言代码无法终止输入并输出结果,请求排查问题

问题排查与解决

你的代码逻辑本身是正确的,但无法输出统计结果的核心原因是EOF(输入结束)的触发方式不对,另外代码里还有一处语法错误需要修正:

1. 修正语法错误

你代码中的printf语句里,字符串直接换行(未使用\n转义),这会导致编译失败。比如:

printf("Enter your sentence (press Ctrl+D to stop the input):
");

需修改为:

printf("Enter your sentence (press Ctrl+D to stop the input):\n");

同理,后续输出语句里的换行也要替换成\n:

printf("The number of words was found to be: %d\n", nw);
printf("The number of characters was found to be: %d\n", nc);
printf("The number of lines was found to be: %d\n", nl);

2. 正确触发输入结束(EOF)

不同操作系统触发EOF的方式不同,你的代码提示只标注了Ctrl+D,Windows用户按此无效:

  • Linux/macOS:输入完成后,按Ctrl+D(若当前行还有输入,需按两次;新行开头按一次即可)
  • Windows:输入完成后,按Ctrl+Z,再按回车

输入结束后,循环会退出,程序随即输出统计结果。

3. 可选:强制刷新输出缓冲(应对极端情况)

若遇到输出迟迟不显示的情况,可在printf后添加fflush(stdout);强制刷新输出缓冲,比如:

printf("Enter your sentence (press Ctrl+D to stop the input, Ctrl+Z on Windows):\n");
fflush(stdout);

修正后的完整代码:

#include <stdio.h>

#define IN 1
#define OUT 0

int main() {
    int c, nl = 0, nw = 0, nc = 0, state = OUT;

    printf("Enter your sentence (press Ctrl+D to stop the input, Ctrl+Z on Windows):\n");
    fflush(stdout);

    while ((c = getchar())!= EOF) {
        nc++;

        if (c == '\n') {
            nl++;
            state = OUT;
        } 
        else if (c == ' '|| c == '\t') {
            state = OUT;
        } 
        else if (state == OUT) {
            state = IN;
            nw++;
        }
    }

    printf("The number of words was found to be: %d\n", nw);
    printf("The number of characters was found to be: %d\n", nc);
    printf("The number of lines was found to be: %d\n", nl);

    return 0;
}

内容的提问来源于stack exchange,提问作者Suryansu Sanjeebani mohanty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:02:42