繁体   English   中英

使用EOF和getchar()计算字符数

[英]Using EOF and getchar() to count the number of characters

我正在尝试编写一个程序来计算 C 中的字符数。 下面是我的程序:

#include <stdio.h>


int main(void){

    
    // long nc;

    // for(nc = 0; getchar() != EOF; nc++);

    // printf("%ld\n", nc);

    long nc;

    nc = 0;
    while(getchar() != EOF){

        ++nc;
    }

    printf("%ld\n", nc);

    return 0;
}

当我使用输入执行上述程序时:-

123<Enter>

然后我在我的 Mac 上按 control + ^d 来表示 EOF,我将 output 设为 4D 而不是 4。谁能告诉我为什么我的 output 中得到 D?

[将我的评论变成答案]

“问题”是终端程序本身写入 output ^D作为对Ctrl-D的响应。

使用程序的原始 output(没有额外的前导换行符),程序将其 output 4写入终端写入的^上。 然后,程序中的(尾随)换行符使终端 go 到 shell 接管并提示写入的下一行。

这将使您的程序的 output看起来像是4D

作为一种可能的解决方案,您可能需要检查终端程序的设置,看看是否可以禁用它自己的 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM