一个统计单词的程序

版权声明:本文为博主原创文章,未经博主允许不得转载! https://blog.csdn.net/weixin_42839965/article/details/89366634
1、编写一个统计单词数量的程序,同时还可以统计字符数和行数。
	选用一个文本中不常用的字符(如,|)作为输入的末尾标记。
	a、统计行数,程序要检查换行字符。
	b、将一个单词定义为一个不含空白(即,没有空格、制表符或换行符)的字符序列。
	当程序读到的第一个非空白字符即是一个单词的开始,当读到空白字符时,结束。
	c、查找一个单词是否有某个字符,可以在程序读入单词的首字符时把一个标记
	(记为inword)设置为1,也可以在此时递增单词计数。然后只要inword为1(或true),
	后续的非空白字符都不记为单词的开始。下一个空白字符,重置inword为0(或false),
	然后程序就准备好读取下一个单词。
	d、在每次读到单词的开头时把inword设置为1(真),在读到每个单词的末尾时把inword设置
	为0(假)。只有在标记从0设置为1时,递增单词计数。
		伪代码:
		如果c不是空白字符,且inword为假
			设置inword为真,并给单词计数
		如果c是空白字符,且inword为真
			设置inword为假
#include <stdio.h>
#include <ctype.h>		//为isspace()函数提供原型
#include <stdbool.h>	//为bool、true、false提供定义
#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("character =%ld,words=%d,lines=%d,", n_chars, n_words, n_lines);
	printf("partial lines=%d\n", p_lines);

	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42839965/article/details/89366634