getchar example from K&R C does not work properly -
i wondering what's happening in code k&r c:
#include <stdio.h> int main() { double nc; (nc = 0; getchar(); ++nc) { ; } printf("%.0f\n", nc); } when run code (os x el capitan), for loop doesn't finish , can't printf statement.
the getchar() returns obtained character on success or eof on failure. reference here.
try this
for (nc = 0; getchar() != eof; ++nc) { } note that, enter doesn't means eof, means newline or '\n'.
look @ header stdio.h, says,
#define eof (-1) here can see how simulate eof.
windows: ctrl+z unix : ctrl+d so long story short, can put condition in for loop,
for (nc = 0; getchar() != '\n'; ++nc) { } // break loop if enter pressed (nc = 0; getchar() != 'c'; ++nc) { } // break loop if c pressed . . .
Comments
Post a Comment