can someone explain to me why I don't get an output running the following code:
Code:#include <stdio.h>/* count characters in input; 2nd version */ main() { double nc; for (nc = 0; getchar() != EOF; ++nc) ; printf("%.0f\n", nc); }
can someone explain to me why I don't get an output running the following code:
Code:#include <stdio.h>/* count characters in input; 2nd version */ main() { double nc; for (nc = 0; getchar() != EOF; ++nc) ; printf("%.0f\n", nc); }
You need to press either ctrl-z (DOS/Windows) or ctrl-d (Unix/Linux) to signal the EOF condition to the input stream.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
You need to terminate the loop by causing it to read and find that end of file has been reached, e.g., by piping in input from the command line instead of interactively entering it, or by triggering it for interactive input by entering CTRL + D or CTRL + Z (depending on your system) on a new line.
Also, note that your loop has a stray semi-colon that makes it such that the loop body is empty, whereas you probably want the statement containing the printf call to be the loop body. Fixed and properly formatted, your program might look like this:
The return 0; is optional if compiling with respect to C99 or later as a special case for the main function. Note that I explicitly defined the main function as returning an int and having no parameters.Code:#include <stdio.h> /* count characters in input; 2nd version */ int main(void) { double nc; for (nc = 0; getchar() != EOF; ++nc) printf("%.0f\n", nc); return 0; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Why are you using a double instead of an integer type for counting?