tags:

views:

97

answers:

5

Hey, so I've wrote two programs in C to count characters and print the value but neither seem to work. One uses the while loop and the other uses for, no errors are reported while compiling, but neither print the total count. Or anything for that matter.

Here's the code using while:

#include <stdio.h>

/* count characters and input using while */
main()
{
    long nc;

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

And here's the code using for:

#include <stdio.h>

/* count characters and input using for */
main()
{
    long nc;

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

Both compile ok and run. When I type input and hit enter, a blank newline prints. When I simply hit enter without inputting anything, again a blank newline prints (and I'd think it would at least print zero). I'm at a loss as to why, everything seems ok... so if you could help me out here I'd really appreciate it.

+4  A: 

You need to terminate the input to your program (i.e. trigger the EOF test).

You can do this on most unix terminals with Ctrl-D or Ctrl-Z at the start of a new line on most windows command windows.

Alternately you can redirect stdin from a file, e.g.:

myprogram < test.txt

Also, you should give main a return type; implicit int is deprecated.

int main(void)
Charles Bailey
Thanks Charles. I was hitting Ctrl-Z when it was Ctrl-D. Everything is working now :).And if implicit int is deprecated, should I also be doing return 0;?
MW2000
@MW2000: You get an implicit `return 0;` if you don't have one in main but personally I think it's better to make it explicit.
Charles Bailey
+1  A: 

Your programs will only output after seeing an end of file (EOF). Generate this on UNIX with CTRL-D or on Windows with CTRL-Z.

Peter G.
A: 

Pressing Enter on your keyboard, adds the character \n to your input. In order to and the program and have it print out the number of characters you would need to add an 'End of File' (EOF) character.

In order to inject an EOF character, you should press CTRL-D in Unix or CTRL-Z on Windows.

KLee1
A: 

You wait for an EOF character (end of file) here. This will only happen in two scenarios:

  • The user presses Ctrl+Break (seems to work on Windows here, but I wouldn't count on this).

  • The user enters a EOF character (can be done with Ctrl+Z for example).

A better way to do this would be to check for a newline instead.

schnaader
A: 

You do realize that newline is a normal character, and not an EOF indicator? EOF would be Ctrl-D or Ctrl-Z on most popular OSes.

ninjalj