Yufei Liu Yufei Liu - 1 year ago 82
C Question

While loop bugs in C

I'm reading the book and I followed the small program in the book, there is a small counting program in which I can't have results.

#include <stdio.h>

int main() {

long nc;

nc = 0;
while(getchar() != EOF)
printf("%ld\n", nc);

When I run this and type in some characters, there is no result, and the program is still executing, I can type in characters but still no result.
Are there anything wrong in the code?

And I'm running it in Xcode.

Answer Source

First of all, if in case you forgot, you need to include the stdio.h header file and secondly, there is nothing wrong with the codes.

while(getchar() != EOF)

The lines of code above checks for end of file and if it returns false, it increments nc and its only when the while loop encounters an end of file before it prints nc. End of file in linux is Ctrl+D and so after inputting your characters, type Ctrl+D and you will have your count since thats the end of file or say input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download