0

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)
        ++nc;
    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.

Yufei Liu
  • 21
  • 1
  • 5

2 Answers2

1

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)
    ++nc

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.

Derick Alangi
  • 1,080
  • 1
  • 11
  • 31
1

The code is fine, if you have the required header files included:

#include <stdio.h>

To exit the while loop, you should send a 'EOF' to the program.

There's a case you can reference What is EOF in the C programming language?.

On Linux systems and OS X, the character to input to cause an EOF is Ctrl-D. For Windows, it's Ctrl-Z.

Community
  • 1
  • 1
CWLiu
  • 3,913
  • 1
  • 10
  • 14