#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<map>
//建立转换映射
std::map<std::string, std::string> bulidMap(std::ifstream &);
//生成转换文本
const std::string&
transform(const std::string&, const std::map<std::string, std::string>&);
//主体函数
void word_transform(std::ifstream& map_file, std::ifstream& input) {
auto trans_map = bulidMap(map_file); //保存转换规则
std::string text; //保存输入的每一行
while (getline(input, text)) { //读取每一行输入
std::istringstream stream(text); //读取每个单词 /*调用sstream的构造函数,创建stream对象保存text的一个拷贝*/
std::string word;
bool fristword = true; //控制是否打印空格
while (stream >> word) {
if (fristword)
fristword = false;
else
std::cout << " "; //单词之间打印空格
//转换并打印输出
std::cout << transform(word, trans_map);
}
std::cout << std::endl; //完成一行的输入
}
}
//转换映射函数的实现
std::map<std::string, std::string> bulidMap(std::ifstream& map_file) {
std::map<std::string, std::string> trans_map;
std::string key;
std::string value;
//读取第一个单词存入key中,行内剩余内容存入value
while (map_file >> key && getline(map_file, value)) {
if (value.size() > 1) { //getline不会跳过前导空格
trans_map[key] = value.substr(1); //跳过前导空格
} //s.substr(pos,n),返回包含从pos开始的n个字符的拷贝的string,n的默认值是s.size()-pos
else {
throw std::runtime_error("no rule for " + key); //抛出异常
}
}
return trans_map;
}
//生成文本函数的实现
const std::string&
transform(const std::string& s, const std::map<std::string, std::string>& m) {
auto map_it = m.find(s); //返回迭代器
if (map_it != m.cend())
return map_it->second;
else
return s;
}
文件流初始化方式https://blog.csdn.net/c_base_jin/article/details/79360909