简体   繁体   中英

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. 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). 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. 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. maybe you just forgot the int before main and return 0 ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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