c - 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;
}
解决方案
在任何 stdio 函数获得 EOF 后,所有未来对它们的调用也只会给出 EOF,即使现在有更多内容。这是标准要求的。幸运的是,该标准还提供了一个解决方案:调用clearerr
并且 EOF 标志将被重置。
推荐阅读
- reactjs - React:如何实现事件侦听器方法以从父组件中删除子组件
- youtube-api - 是否可以通过 YouTube Live Streaming API 设置直播的类别?
- algorithm - 为什么 BFS 总是给出曼哈顿距离?
- javascript - 需要 Angular 8 canActivate 才能返回 Observable
主题的 - publish-profiles - ExcludeFilesFromProject 在 Visual Studio 中不起作用
- angular - 在 Angular 应用程序中显示消息
- python - 在 Python 中组合多个 CSV
- javascript - 赛普拉斯拦截 - 在同一测试用例中使用不同的有效负载多次执行相同的 api
- git - 忽略子模块内的文件
- python - 如何从 python 中的字典列表创建 CSV 文件