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
).