I have a program here that counts new lines, words, and characters. I get keyboard input from the user using getchar() as a condition in a while loop. After the while loop I display the number of new lines, words, and characters. My only problem is I don't know what keyboard input I should enter in order for the condition (c = getchar()) != EOF to be false. I checked what value EOF is by printing it, it printed -1, so I thought in order to step out of the while loop all I have to type in is -1, but the program still doesn't step out of the while loop to print the result. What should I do?
Code:
#include <cstdio>
#define IN 1 // inside a word
#define OUT 0 // outside a word
int main() {
// count lines, words, and characters in input
int c = 0; // hold the character being checked
int nc = 0; // hold count for new character
int nl = 0; // hold count for new line
int nw = 0; // hold count for new word
int state = 0;
state = OUT;
while ((c = getchar()) != EOF) {
// increment nc unconditionally
++nc;
// check for a new line
if (c == '\n') {
++nl;
}
// if c is space, tab, or new line, state will not be inside a word
if (c == ' ' || c == '\t' || c == '\n') {
state = OUT;
} else if (state == OUT) {
++nw;
state = IN;
}
} // end of while
// print the number of new lines, characters, and words
printf("There are %d new lines, %d characters, and %d words", nl, nc, nw);
} // end of main
Last edited: