标准库小练习(自己动手写单词统计程序)

在一段文字中,统计给定单词的所在行数
题目来自于c++primer 第五版 P430 :使用标注库:文本查询程序

#include <iostream>
#include <unordered_map>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
	ofstream out("C:\\Users\\MLL\\Desktop\\test.txt");//打开文件,写入需要进行查询的文档(路径名需要更改成自己的)
	try//用try语句块负责异常处理
	{
		if (!out.is_open())
		{
			throw runtime_error("open file fail 1");//未打文件则开抛出异常
		}
		string str;
		while (getline(cin, str))//用getline从标准输入读取文档
		{
			out << str << '\n';//getline一次读取一整行,但是行末的换行符会被丢弃,这里主动加上换行符
		}
	}
	catch (runtime_error err)
	{
		cout << err.what() << endl;//.what()输出err的内容
	}
	out.close();//关闭文件
	ifstream in("C:\\Users\\MLL\\Desktop\\test.txt");//ifstream文件流读取刚才写入的文档(路径名需要更改成自己的)
	unordered_map<string, string> m;//第一个string保存单词,第二个string用字符串的形式保存单词所在行数
	try
	{
		if (!in.is_open())
		{
			throw runtime_error("open file fail 2");//未打文件则开抛出异常
		}
		string str;
		istringstream iss;//string流读取
		int i = 1;
		while (in)
		{
			getline(in, str);//getline从文件流里读取一整行,并将其传递给str
			iss.str(str);//将str拷贝给iss流
			string t;
			while (iss >> t)//流读取失败后failbit会被置位,导致后面的流使用失败  t一次接受一个string直到iss遇到流末尾    
			{
				m[t] += " " + to_string(i);//to_string(i)将i转换为string的形式,string相加会合并成为一个string,用这种方式可以把单词出现的行数合并在一起
			}
			iss.clear();//流复位才能继续使用istringstream,因为上面while循环里的iss读取失败,failbit置位
			++i;
		}
	}
	catch (runtime_error err)
	{
		cout << err.what() << endl;
	}
	cin.clear();//同样是对cin流置位,如果不把流复位,之后的cin都会失败,导致出现死循环(因为前文在使用getline的时候ctrl+z结束了读取)
	string f, world;
	cout << "the world that you need to find" << endl;
	char flag = 'Y';//循环条件
	while (flag == 'y' || flag == 'Y')
	{
		cin >> world;
		if (m.find(world) != m.end())//查找并输出
		{
			auto a = m.find(world);
			cout << "the result is:" << endl;
			cout << "the world:  '" << a->first << "'  appear at line:" << a->second << endl;
		}
		else
		{
			cout << "can't find the world at txt" << endl;
		}
		cout << "want to continue? 'Y' or 'N' " << endl;
		cin >> flag;
	}
	in.close();
	system("pause");
}

可以通过windows的txt文本文档的查找功能判断程序是否运行正确

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值