首页 > 解决方案 > CTRL-D 退出程序而不是循环

问题描述

在逐个字符读取输入时,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;
}

标签: c

解决方案


在任何 stdio 函数获得 EOF 后,所有未来对它们的调用也只会给出 EOF,即使现在有更多内容。这是标准要求的。幸运的是,该标准还提供了一个解决方案:调用clearerr并且 EOF 标志将被重置。


推荐阅读