C++ primer 第五版 中文版 练习 11.33 个人code

C++ primer 第五版 中文版 练习 11.33

题目:实现你自己版本的单词转换程序。

答:

#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <sstream>

using namespace std;

//读入给定文件,建立起转换映射。
map<string, string> buildMap(ifstream &map_file)
{
	map<string, string> trans_map; //保存转换规则。
	string key; //要转换的单词。
	string value; //替换后的内容。
	//读取第一个单词存入key中,行中的剩余内容存入value。
	while (map_file >> key && getline(map_file, value))
	{
		if (value.size() > 1)
			trans_map[key] = value.substr(1);
		else
			throw runtime_error("no rule for " + key);
	}

		return trans_map;

}

//接受一个string,如果存在转换规则,返回转换后的内容,如果不存在,则返回原字符。
const string &transform(const string &s, const map<string, string> &m)
{
	auto map_it = m.find(s);
	if (map_it != m.cend())
		return map_it->second;
	else
		return s;
}

//接受两个文件名参数:第一文件名参数对应规则文件,第二个文件名参数对应想要转换的文件。
void word_transform(ifstream &map_file, ifstream &input)
{
	auto trans_map = buildMap(map_file); //保存转换规划 等同于: map<string,string> trans_map = buildMap(map_file);
	string text; //保存想要转换文件中的第一行。
	while (getline(input, text))  //读取一行内容。
	{
		istringstream stream(text);   //把每一行的每个单词初始化至 string流中。
		string word;
		bool firstword = true;
		while (stream >> word)   //将string 流中的单词写入 word
		{
			if (firstword)
				firstword = false;
			else
				cout << " ";
			cout << transform(word, trans_map);  //根据规则转换单词。
		}
		cout << endl;
	}
}

//用包含参数的main函数来测试:第一个文件为转换规则,第二个文件为想要转换的文件。

int main(int argc,char ** argv)
{
	ifstream trans_file(argv[1]);
	ifstream input_file(argv[2]);

	word_transform(trans_file, input_file);
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值