给出一段英文,统计单词出现的次数

本文介绍了一个使用C++实现的简单程序,该程序能够读取用户指定的文本文件,并统计每个单词出现的频率,最后将统计结果保存到另一个文件中。程序使用了标准模板库(STL)中的map容器来存储单词及其对应的计数。

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

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

int main()
{
	string filename;
	cin>>filename;
	ifstream input(filename,ios::in);//打开文件
	if(input.fail())
	{
		cout<<"打开文件失败,请检查输入是否正确!\n";
		system("puase");
		return 0;
	}
	map<string, int> wordCount;  //关联容器
	string word;
	while (input>> word)  //统计单词出现次数
		++wordCount[word];
	input.close();  //关闭文件
	string result;
	cout<<"请输入保存统计结果的文件名!\n";
	cin>>result;
	ofstream output(result,ios::out);  //创建文件
	if(output.fail())
	{
		cout<<"创建文件失败!\n";
		system("puase");
		return 0;
	}
	//向指定文件输出统计结果
	for (map<string, int>::iterator it = wordCount.begin(); it != wordCount.end(); ++it)
		output<<(*it).first<<' '<<(*it).second<<"次"<<endl;
	output.close();//关闭文件
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值