Counting characters in input with while loop
I wrote a simple c program to count the number of characters
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
This program does not print characters for me. While testing various cases, I found myself stuck in an infinite loop while()
.
source to share
This program does not print characters for me
This is not true. You have not added any instructions for printing them. In the meantime, there is no need to worry about it.
I found myself stuck in an endless loop
If you don't get into a hacked state, you will find yourself in a loop. To get out of the loop, you must receive EOF
. use
- CTRL+ Z(on windows)
- CTRL+ D(on linux)
Now the solutions:
-
getchar()
will not print values. You should store the values ββand print explicitly (if you like), perhapsputchar()
. -
You either supply
EOF
or change the interrupt conditionwhile()
to break out of the main infinite loop.
Besides coding problems, you also need to think about logic. In this form of code, getchar()
it is also considered a newline character ( \n
) as a valid character. To explain, input in the form
$. / a.out ENTER
ENTER
s ENTER
d ENTER
e ENTER
r ENTER
CTRL+D
There will be a result
ten
but this is not what we usually call character counting. You can also view this piece of logic.
However, the recommended signature main()
is int main(void)
.
source to share