Possible Duplicate:
Why doesn’t getchar() recognise return as EOF in windows console?
I'm trying to print out the value in the variable 'nc' in the next program:
int main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
Please tell me why is it not printing?
You don't have brackets in your while loop (this is why not using brackets leads to error prone software). Therefore, the value is getting incremented, but not printing.
Try:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{ // ADD THIS
++nc;
printf("%ld\n", nc);
} // AND THIS
}
otherwise, your code is essentially doing:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{
++nc; // ENDLESSLY ADDING
}
printf("%ld\n", nc); // NEVER REACHED DUE TO WHILE LOOP.
}
Your while loop will continue to loop until you end the input using Control-D on Unix or Control-Z, Return on Windows. It will do this without printing anything because you did not use braces around the ++nc and printf.
You may also have problems with printf if you did not #include <stdio.h> at the top of your program. If the compiler does not know that printf is a varargs function, it will not format the argument list correctly when calling it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With