4、编写一个程序,把输入作为字符流读取,直到遇到EOF。统计每个单词的平均字母数,不包含空格、标点符号等
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
int input; //输入变量
int words_count = 0; //统计单词个数
int characters_count = 0;//统计字符个数
bool word_flag = false; //单词默认设置为假
printf("请输入:");
while ((input = getchar()) != EOF) //如果不到文件末尾就一直输入,EOF为文件末尾,一般是 Ctrl + C 或者 Ctrl + D;
{
if (!isspace(input) && !ispunct(input)) //输入如果既不是空格 又不是标点符号 的话,统计的字符个数+1
{
characters_count++;
if (!word_flag) { //因为默认是false,所以这里要取反设置为真,不输入空格分割的话就是一个单词。
words_count++;
word_flag = true;
}
}
if (isspace(input) || ispunct(input)) //如果输入了 空格 或者 标点符号 的话就分割了连续的字符,那也就是说当前这个单词拼写完了,再把 word_flag 置为 false;
{
word_flag = false;
}
}
printf("%d character are read.\n",characters_count);
printf("%d words are read.\n", words_count);
printf("The average number of each word are %.2f.\n", (float)characters_count / (float)words_count);
return 0;
}