用C语言写一个统计单词的程序

2021/8/3 17:06:34

本文主要是介绍用C语言写一个统计单词的程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

编写一个统计单词数量的小程序,该程序可读取并报告单词的数量。

  1. 该程序要逐个字符读取输入,知道何时停止读取。
  2. 该程序能识别并计算这些内容:字符、行数和单词。
#include <stdio.h>
#include <ctype.h>		//为isspace()函数提供原型
#include <stdbool.h>	//为bool、true、false提供定义
#define STOP '|'
int main(int argc, char const *argv[])
{
	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:\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("partiial lines = %d\n", p_lines);

	return 0;
}


这篇关于用C语言写一个统计单词的程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程