agongji
agongji

Reputation: 191

Counting the number of characters in C language

I am a beginner of C language, and now trying to count the number of characters which is input.

#include <stdio.h>

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

This is what I wrote just as my textbook writes, but printf function doesn't seem to work.

In addition, this program doesn't seem to finish, because the prompt is not coming up.

I have no idea if the contents of this book are old enough.

Could you tell me what is wrong with this code?

Upvotes: 1

Views: 244

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755054

This looks like code from K&R The C Programming Language, 2nd Edn (1988), Chapter 1, p18.

The problem is that your transcription of the code is misinterpreting %ld as %1d. Given that nc is of type long, you need %ld (letter ell) and not %1d (digit one). The book contains an ell and not a one.

With suitable options, compilers like GCC and Clang will give warnings about type mismatches in the format strings. Use -Wall -Werror to get errors when the code is malformed (or -Wformat if you can't work with -Wall — but I use -Wall -Wextra -Werror plus a few extra fussier options for all my compilations; I won't risk making mistakes that the compiler can tell me about).

The use of main() shows that the book is dated. C99 requires a return type and prefers void in the argument list — int main(void) — when you don't make use of the command line arguments.

As to the program not finishing, when you're typing at the terminal, you indicate EOF (end of file) to the program by typing Control-D on most Unix-like systems (though it is configurable), and Control-Z on Windows systems. (If you want to indicate EOF without typing a newline immediately beforehand, you need to type the EOF indicator twice instead of just once.) Or you can feed it a file from the shell: counter < data-file (assuming the program is called counter and you want to count the characters in the file data-file).

Upvotes: 3

Related Questions