My code does not return any value. Can anyone help me explain why it does not work?
#include<stdio.h>
int main()
{
int nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%1d\n", nc);
}
My code does not return any value. Can anyone help me explain why it does not work?
#include<stdio.h>
int main()
{
int nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%1d\n", nc);
}
You have to input EOF
to get out of the loop.
Windows: Ctrl+Z
Linux : Ctrl+D
See C : How to simulate an EOF?
Only after getchar()
returns EOF
will the value of nc
be printed.
And %1d
is effectively same as %d
as a number has at least one digit.
If you do %10d
or something the number would be printed occupying the space that would've been occupied by a 10 digit number. Default alignment is right.
You can make it left aligned with %-10d
I think you're missing the input when you run the code. You have to type in the console after compilation is done. Right now it's not getting any input character to count.
The same code works for me. You can check the below ideone screenshot where same code is returning the correct output .