TangoKilo
TangoKilo

Reputation: 1785

Why is this not producing any output when using printf()?

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

Upvotes: 0

Views: 297

Answers (2)

brice
brice

Reputation: 25029

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

Upvotes: 4

Przemyslaw Zych
Przemyslaw Zych

Reputation: 2060

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.

Upvotes: 2

Related Questions