简体   繁体   English

为什么在 while 循环之后 printf() 不起作用?

[英]Why printf() after the while loop would not work?

I'm a beginner and I've recently started learning C and here is an example in " The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie " that I don't understand.我是一个初学者,我最近开始学习 C,这里是“ C 编程语言,Brian W. Kernighan,Dennis M. Ritchie ”中的一个我不明白的例子。 This program is supposed to count new lines in input and print out the final result.该程序应该计算输入中的新行并打印出最终结果。 This is the exact same program that is in the book (page 19).这与本书(第 19 页)中的程序完全相同。 The output of it is nothing.它的输出什么都不是。 I can input forever and it just goes to a new line...我可以永远输入,它只是转到一个新行...

main()
{
    int c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c == '\n')
            ++nl;
    printf("%d\n", nl);
}

If I put the "printf("%d\\n", nl)" statement in the body of the if statement, the output would be printed each time on a new line and the value of "nl" wouldn't reset either.如果我将 "printf("%d\\n", nl)" 语句放在 if 语句的主体中,则每次都会在新行上打印输出,并且 "nl" 的值也不会重置。 it just increments every time I input something and the program wouldn't terminate.每次我输入内容时它都会增加并且程序不会终止。

Why doesn't the example work?为什么示例不起作用?

int main()
{
    int c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c == '\n')
            ++nl;
    printf("%d\n", nl);
  return 0;
}

I ran it on my computer using Code::Blocks and it worked just fine.我使用 Code::Blocks 在我的计算机上运行它,它运行得很好。 maybe you just forgot the int before main and return 0 ^^也许你只是忘记了 main 之前的 int 并返回 0 ^^

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

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