以下代码逐个字符地从stdin
流中读取,直到遇到EOF符号(CTRL-D)。但是,当我执行CTRL-D命令时,它不会将其作为EOF字符进行处理。
#include <stdio.h>
#include <ctype.h>
int main() {
char current_character, next_character;
int amount_of_characters = 0, amount_of_words = 0, amount_of_newlines = 0;
while( (current_character = getchar()) != EOF) {
amount_of_characters++;
if(isspace(current_character) || current_character == '\n') {
next_character = getc(stdin);
if(isalpha(next_character)) {
amount_of_words++;
ungetc(next_character, stdin);
}
if(current_character == '\n') {
amount_of_newlines++;
}
}
}
printf("----- Summary -----\n");
printf("Characters: %d\nWords: %d\nNewlines: %d\n", amount_of_characters, amount_of_words, amount_of_newlines);
return 0;
}