The code below is my answer to exercise 1-13 in K&R The C Programming Language, which asks for a histogram for the length of words in its input. My question is regarding EOF. How exactly can I break out of the while loop without ending the program entirely? I have used Ctrl-Z which I have heard is EOF on Windows, but this ends the program, instead of just breaking the while loop. How can I get to the for loop after the while loop without ending the file? This is a general question, not just with my code below but for all the code in K&R that uses: while ((c = getchar()) != EOF). Thanks in advance! `
#include <stdio.h>
#define MAXLENGTH 20 /* Max length of a word */
#define IN 1 /* In a word */
#define OUT 0 /* Out of a word */
int main() {
int c, i, j, len = 0;
int lenWords[MAXLENGTH];
bool state = OUT;
for (i = 0; i < MAXLENGTH; ++i) {
lenWords[i] = 0;
}
c = getchar();
while (c != EOF) {
if (c != ' ' && c != '\n' && c != '\t') {
if (state == IN) {
lenWords[len - 1] += 1; /* a length 5 word is in subscript 4 */
len = 0;
}
state = OUT;
}
else {
state = IN;
}
if (state == IN) {
len += 1;
}
c = getchar();
}
/* Generating a histogram using _ and | */
for (i = 0; i < MAXLENGTH; ++i) { /* Underscores write over one another; not so efficient */
for (j = 0; j < lenWords[i]; ++j) {
putchar('_');
}
putchar('\n');
for (j = 0; j < lenWords[i]; ++j) {
putchar('_');
}
putchar('|');
printf("Length: %d, Frequency: %d", i + 1, lenWords[i]);
}
return 0;
}
I think your question belongs on another network.
Answers here: Equivalent to ^D (in bash) for cmd.exe?
No. CtrlD on *nix generates a EOF, which various shells interpret as running
exit. The equivalent for EOF on Windows is CtrlZ, but cmd.exe does not interpret this specially when typed at the prompt.
You have to check whether you use *nix or windows.
On Windows, EOF is represented by Ctrl+Z, whereas on *nix EOF is represented by Ctrl+D