c - 在从标准输入读取的while循环中捕获EOF字符
问题描述
以下代码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;
}
解决方案
推荐阅读
- javascript - 滚动在 Firefox 中不起作用,我有一个表格,当用户向下滚动时会加载更多,但它会在 Firefox 中停止
- powerbi - 日期间隔中的剩余工作日
- firebase - 不使用拉刷新进行更新,而是重复旧数据
- c++ - 如何动态添加模板参数
- python-3.x - 什么是 ray::IDLE,为什么有些工作人员内存不足?
- laravel - Laravel - 如何验证请求规则中另一个表的字段
- java - 上传多个文件时HTTP/2是否支持多路复用
- python-3.x - 使用 pyinstaller 获取规范文件而不是 exe
- sql - 使用交叉应用选择不会返回预期的结果
- ruby-on-rails - ManageIQ / Cloudforms 动态表单