【C++】编程实现计算英文文献的行数与单词数

要求

编写一程序,统计一篇英文文章中单词的个数与行数。

代码

#include <iostream>
#include "fstream"
using namespace std;

#define FILEPATH "test.txt"

//文章信息结构体
struct TextInfo 
{
	int num_of_words;
	int num_of_lines;
};

//判断是否为英文单词,word里面what's 代表一个单词
bool isEnglishWords(char c)
{
	return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '\'');
}

//编写一程序,统计一篇英文文章中单词的个数与行数。
TextInfo compteWordsAndLines()
{
	TextInfo ti;
	ti.num_of_lines = 0;
	ti.num_of_words = 0;
	//单词的个数,有空格就算一个单词
	//首先以只读的形式打开文章
	ifstream fin;
	fin.open(FILEPATH);
	if (fin.fail())
	{
		cout << "empty file 1" << endl;
		fin.close();
	}

	char buf[1024] = {};
	int lines = 0;
	int words = 0;
	bool inword = false;
	int i = 0;
	while (!fin.eof()) 
	{
		fin.getline(buf, 999);
		lines++;
		i = 0;
		inword = false;
		while (buf[i] != 0) //不为行尾
		{
			if (!isEnglishWords(buf[i]))
				inword = false;
 			else if (isEnglishWords(buf[i]) && inword == false) {
				words++;
				inword = true;
			}
			i++;
		}
	}

	ti.num_of_lines = lines;
	ti.num_of_words = words;

	fin.close();
	return ti;
}
int main()
{
	TextInfo myti = compteWordsAndLines();
	cout << myti.num_of_lines << endl;
	cout << myti.num_of_words << endl;

	cout << "hello world!" << endl;
	system("pause");
	return 0;
}

关于文件读写

需要熟练掌握文件读写的函数,看到这篇文章一次,就回顾一次吧。


版权声明:本文为weixin_45066412原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。