0

I'm going through K&R C at the moment and I'm trying out an example in which the program takes a stream of characters as an input, and then prints the number of characters there are in the stream.

This doesn't seem to produce any output as far as I can see:

main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF){
         ++nc;
    }
    printf("%1d\n", nc);
}

However this seems to work fine albeit, slightly differently from what I want:

main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF){
         ++nc;
         printf("%1d\n", nc);
    }
}

Any pointers would be much appreciated. Thanks in advance!

EDIT

I've attempted simulating an EOF using ctrlz but that doesn't appear to be working. I'm running this off the cmd line on Windows 7 if that makes any difference. enter image description here

9
  • How are you closing the input stream?
    – Mat
    Commented May 2, 2013 at 10:21
  • Add getch(); after the printf
    – 999k
    Commented May 2, 2013 at 10:23
  • 2
    If your printf works inside the while loop but not out then it's never receiving an EOF. Commented May 2, 2013 at 10:23
  • What does your debugger say?
    – bash.d
    Commented May 2, 2013 at 10:24
  • "%1d\n" ---> "%ld\n"
    – BLUEPIXY
    Commented May 2, 2013 at 10:24

2 Answers 2

4

Your program works fine.

You are not seeing the output because you never send EOF. If you're running on the command line, either pass in a file:

./a.out <myfile.txt

(This will also work on Windows)

Or, if you're typing your input in yourself, type <return><ctrl-D><return> to send an EOF. (or <return><ctrl-Z><return> on Windows)

This should then work as expected.

➤ cat try.c
#include <stdio.h>
main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF){
         ++nc;
    }
    printf("%1d\n", nc);
}
➤ gcc try.c -o try && ./try <try.c
131

Here's an example session with GnuCC.

control-Z working with minGW

2

For getchar to return EOF you need to "close the stream/reach the end of stream". See answers to this question: C : How to simulate an EOF?

In short: you need to send EOF to the stream (e.g. by sending Ctrl+Z on Windows or Ctrl+D on Linux). Or e.g. useing pipes. For example pipe contents of one file to your application. When the first application terminates it automatically closes the stream so your application will read EOF.

e.g. Under Linux:

$ cat some_file.txt | ./a.out

Hope this helps.

Not the answer you're looking for? Browse other questions tagged or ask your own question.