使用for循环计数c中的单词长度时出乎意料的结果



我正在学习C语言,并且该程序是关于不计算字符的。

这是代码

#include <stdio.h>
int main(void) {
    // your code goes here
    double nc;
    for (nc=0;getchar() != EOF;nc++);
    printf("%.0fn", nc);
    return 0;
}

输入

''

无输入。

我要获得的输出为1。

在线编译器结果

不应输出等于0,而不是1.不可能理解为什么要来。

谢谢

如果您在编程中付出了更多努力,添加几行代码,一切都将很清楚:

#include <stdio.h>
int main(void) {
    // your code goes here
    int nc;
    int c;
    for (nc=0;(c = getchar()) != EOF;nc++)
    {
        printf("The char is '%c' code: 0x%02xn", c >= 32 ? c : '.', c);
    }
    printf("%dn", nc);
    return 0;
}

https://ideone.com/jfgk7h

和Mistery解决了。您已经按了IDEONE输入框中的Enter,那里有一个新的行。

您是如何输入 input

的。

如果您在键盘上击中<enter>键,则获得了一个n char,导致该响应。

尝试以下操作:

$ a.out
<Ctrl-D>
0
$ _

($是提示,<Ctrl-D>是从UNIX终端产生任何输入的方式(当然,a.out是您程序的名称(您没有显示如何称呼它(

顺便说一句,为什么在printf()中的t中结束输出???t是一个标签字符,而不是新行。...8-.

最新更新