C统计单词程序
需求描述
- 读取并报告单词的数量
- 计算字符数和行数
识别单词的处理
把一个单词定义为不含空白的字符序列
既:没有空格、制表符、换行符
/**
* @Author: Lucifer
* @Date: 4/30/2023, 2:12:10 PM
* @LastEditors: Lucifer
* @LastEditTime: 4/30/2023, 2:12:10 PM
* Description: 识别单词的程序
* Copyright: Copyright (©)}) 2023 Your Name. All rights reserved.
*/
# include<stdio.h>
# include<ctype.h>
# include<stdbool.h>
# define STOP '|'
int main(void)
{
char c; // 读入字符
char prev; // 读入的前一个字符
long n_chars = 0L; // 字符数
int n_lines = 0; // 行数
int n_words = 0; // 单词数
int p_lines = 0; // 不完整的行数
bool inword = false; // 如果字符c在单词中,则inword = true
printf("Enter text to be analyzed( | to terminate): \n");
prev = '\n'; // 识别完整的行
while ((c = getchar()) != STOP)
{
n_chars++; // 统计字符
if (c == '\n')
n_lines++; // 统计行
if (!isspace(c) && !inword)
{
inword = true; // 开始一个新的单词
n_words++; // 统计单词
}
if (isspace(c) && inword)
inword = false; // 达到单词末尾
prev = c; // 保存字符的值
}
if (prev != '\n');
p_lines = 1;
printf("Characters = %ld, words = %d, lines = %d,", n_chars, n_words, n_lines);
printf("partial lines = %d\n", p_lines);
getchar();
getchar();
return 0;
}
标签:字符,inword,int,程序,lines,单词,prev,统计
From: https://www.cnblogs.com/JunkingBoy/p/17371686.html