18.05 统计一个一篇英文小说的单词数,从文件读取小说,统计其英文单词个数,并将个数保存到文件file.txt中

本文介绍了一个简单的C++程序,用于读取文本文件中的字母并计数。通过逐行读取文件,判断每个字符是否为字母,并统计字母出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非原创,参考大部分优快云大佬代码。

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

bool isLetter(char letter) {  //判断字符是不是字母
	if ((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')) {
		return true;
	}
	else {
		return false;
	}
}


int main()
{
	ifstream infile("novel.txt");
	if (!infile)
	{
		cerr << "open novel.txt error!" << endl;
		exit(1);
	}
	char ch[100];
	infile.getline(ch, 100);
	int  count = 0;
	while (ch[0] != '\0') {
		cout << ch<<endl;
		int i = 0;
		while (ch[i] != '\0') {
			//如果起一个字符是字母后一个字符不是字母,那么就可以看成此处有一个单词
			if (isLetter(ch[i]) && !isLetter(ch[i + 1]))
			{
				count++;
			}
			i++;
		}
		infile.getline(ch, 100);
	} 
	infile.close();
	ofstream outfile("file.txt");
	if (!outfile)
	{
		cerr << "open file.txt error!" << endl;
		exit(1);
	}
	outfile<< "总字母为:" << count << endl;
	cout <<"总字母为:" <<count << endl;
	outfile.close();
	return 0;
}





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值