OtterFox Posted August 18, 2007 Posted August 18, 2007 Whenever I run this code the while ((c = getchar()) != EOF) wont end and It keeps asking for more input, I've tried with microsoft visual C++, cygwin+gcc and Linux. #include <stdio.h> int main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for(i = 0; i < 10; ++i) { ndigit[i] = 0; } while ((c = getchar()) != EOF) { if(c >= '0' && c <= '9') ++ndigit[c-'0']; else if(c == ' '|| c == 'n' || c == 't') ++nwhite; else ++nother; } printf("digits ="); for(i = 0; i < 10; ++i) printf(" %d", ndigit[i]); printf(", white space = %d, other = %dn", nwhite, nother); return 0; } if I change it to... ... while ((c = getchar()) != EOF) { if(c >= '0' && c <= '9') ++ndigit[c-'0']; else if(c == ' '|| c == 'n' || c == 't') ++nwhite; else ++nother; printf("digits ="); for(i = 0; i < 10; ++i) printf(" %d", ndigit[i]); printf(", white space = %d, other = %dn", nwhite, nother); } return 0; } It prints the correct output but it also prints it for each loop which is understandable. How do I make it so than when I press enter it returns a EOF? Thanks Quote
cooper Posted August 18, 2007 Posted August 18, 2007 How do I make it so than when I press enter it returns a EOF? Well, you could of course test to see if c now holds the Enter key (well, keys. Enter is chars 10 immediately followed by 13 on Windows, only char 10 on UNIX and only char 13 on Mac IIRC). Ctrl-D I think is what makes getchar return an EOF when it's reading from the keyboard. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.