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;
}