CTRL-D退出程序而不是仅循环

时间:2019-04-26 00:45:58

标签: c

在逐字符读取输入字符时,CTRL-D应激活EOF符号并退出循环并在循环后执行printf语句。但是,CTRL-D会完全退出程序。

#include <stdio.h>
#include <ctype.h>

int main() {

    int 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++;

}

    printf("%d", amount_of_characters);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

在任何stdio函数获得EOF之后,即使现在有更多内容,将来对它们的所有调用也将仅给出EOF。这是标准要求的。幸运的是,该标准还提供了一种解决方案:调用data Natural = A | B | C | D | E | F | G data Note = Note { natural :: Natural , offset :: Int -- positive for sharp, negative for flat, say } ,将重置EOF标志。