Question : Why doesn't this very simple C program not work all the way through?

Hi There,

I'm on OSX and have the gcc command line compiler for the C language.  I am new to C and am therefore using the classic book "The ANSI C Programming Language" by Brian Kernighan and Dennis Ritchei as a way to learn the language.  There is one exercise in the first part of the book that I cannot get working, and I think it may have to do with the way I am compiling, but am not sure.  The program is very simple.  It is intended to simply count the amount of characters from input (in this case, the exercise uses getchar().  Here is the program as found in the book:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
#include <stdio.h>

/*   count characters in input; 1st version */

main()
{
     long nc;

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

After I save that code out to a file named 'characterCount.c' I run the gcc command line tool like so:

gcc characterCount.c

It compiles fine, no errors.  I then run the executable generated by the compiler like so:

./a.out

The program waits for my input, so I type a few characters, hit enter, and nothing prints out.  The program is expecting more input. Why is that?!  Shouldn't the line of code with the printf get executed?  I know this is minor, but I really want to understand why the code is not executing all the way through. Is there some special switch I have to turn on while compiling to make it work?  

Can anybody help me understand what is going on here.  I'm particularly interested in why the program keeps expecting more input after I enter a line of characters.

Thank you for your time and help!

Answer : Why doesn't this very simple C program not work all the way through?

try

while (getchar() != "\n")

EOF should be Ctrl + D I guess...
Random Solutions  
 
programming4us programming4us