K&R练习1-8改进

3

所以程序能够工作,但是它的工作方式如下:

input: 3 blanks
output:
newlines:0
tabs:0
blanks:1
newlines:0
tabs:0
blanks:2
newlines:0
tabs:0
blanks:3
newlines:1
tabs:0
blanks:3

以下是该程序:

#include <stdio.h>

main() {
    int c, nl, t, b;
    nl = 0;
    t = 0;
    b = 0;
    while ((c = getchar()) != EOF) {
        if (c == '\n')
            ++nl;
        if (c == '\t')
            ++t;
        if (c == ' ')
            ++b;
        printf("newlines:%d\ntabs:%d\nblanks%d\n", nl, t, b);
    }
}

我的问题是,是否可以仅显示最后一个结果,其中包含blanks:3,以避免重复。
(newlines:1
tabs:0
blanks:3)?

printf 移到循环外面。 - Spikatrix
主循环之外?无法编译.. - John Doe
1
main() 是一个函数,而不是循环。while 才是循环。此外,我建议使用标准的 int main(void) 签名来定义 main 函数。 - Spikatrix
将其移出 while 循环后,现在完全没有输出。您能否发布代码以准确展示您的意思?为什么使用 (int main(void))? - John Doe
1
我猜你没有发送“EOF”条件。如果你在Windows上,请尝试按下CTRL + Z,然后按回车键;如果你在Linux上,请尝试按下CTRL + D,以发送“EOF”条件,以便循环结束。根据最新的C标准,“int main(void)”是“main”函数的正确签名之一。你正在阅读的书很旧,这就是为什么它只使用了“main()”。 - Spikatrix
显示剩余2条评论
1个回答

0

你应该将 printf("newlines:%d\ntabs:%d\nblanks%d\n", nl, t, b); 这行代码放在 while 循环的结束 } 后面。

注意当代码格式正确时,代码更易读。

还要注意,main 函数必须有一个定义好的返回类型 int

这是修改后的版本:

#include <stdio.h>

int main() {
    int c, nl, t, b;
    nl = 0;
    t = 0;
    b = 0;
    while ((c = getchar()) != EOF) {
        if (c == '\n')
            ++nl;
        if (c == '\t')
            ++t;
        if (c == ' ')
            ++b;
    }
    printf("newlines:%d\ntabs:%d\nblanks%d\n", nl, t, b);

    for(;;);  // infinite loop to keep the output visible

    return 0;
}

需要将 main() 改为 main(void) 吗? - EsmaeelE
@EsmaeelE:两种都是有效的,还有int main(int argc, char *argv[])和兼容的变体。 - chqrlie
是的,这个建议已经提出了,但仍然无法在没有手动按下Ctrl Z的情况下工作 - 没有输出产生。我在gcc和在线c编译器中都尝试过(复制并粘贴了您的代码)。难道没有办法在实际程序中声明EOF吗? - John Doe
此外,EOF 结束程序并不是最优的选择。 - John Doe
@chqrlie 不用担心。;) 再次感谢您的回答! - John Doe
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接