You have to finish the input. Your program will count characters until EOF
is encountered. EOF
, in the keyboard, can be sent by pressing Ctrl-Z then ENTER if you are in Windows, or Ctrl-D then ENTER if you are in Linux/OS X.
Why is getchar() not working for me?
Question
I've just started programming c and I'm working through The C Programming Language by Brian W.Kernighan and Dennis M.Richie.
One of the first examples is character counting and the following program is given, but when I enter a string no result it printed.
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n",nc);
}
Why isn't this working?
Solution
OTHER TIPS
as an addition to the answers that were mentioned , here's how to make your program show results when pressing Enter
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != '\n')
++nc;
printf("%ld\n",nc);
}
getchar()
is buffered input. Since it is buffered, The control will wait until you press
Enter key from the keyboard.
In your program, you are checking for EOF
by doing
while (getchar() != EOF)
On windows, if you want EOF, you have to input a combination of 2 keys. i.e Ctrl+Z. If you are on LINUX, then EOF is combination of 2 keys Ctrl+D
As said earlier, control will wait at console until you press Enter, so you have to press
- Ctrl+Z Enter - on windows.
- Ctrl+D Enter - on LINUX.
You have to send EOF
to program by pressing CTRL+D (for linux) or CTRL+Z (for Windows) to end the while loop.