//练习11.33 #include #include #include #include #include #include using namespace std; //函数buildmap读入给定文件,建立起转换映射 map buildmap(ifstream & mapfile) { map trans_map; //保持转换规则 string key; //要转换的单词 string value; //替换后的内容 //读取第一个单词存入key中,行中剩余内容存入value; while (mapfile >> key && getline(mapfile, value)) { if (value.size() > 1) { trans_map[key] = value.substr(1); //跳过空格那个当 } else throw runtime_error("no rule for" + key); } return trans_map; } const string &Transform(const string & s, const map & m) { //实际的转换工作,此部分是程序核心 auto map_it = m.find(s); //如果单词在转换规则map中 if (map_it != m.end()) { return map_it->second; //使用替换短语 } else return s; //否则返回原string } //单词转换程序 void word_transform(ifstream & mapfile, ifstream & input) { auto trans_map = buildmap(mapfile); //保存转换规则 string text; //保存输入中的每一行 while (getline(input, text)) //读取一行输入 { istringstream stream(text); //读取每一个单词 string word; bool firstword = true; //控制是否打印空格 while (stream >> word) { if (firstword) firstword = false; else cout << " "; //在单词间打印一个空格 cout << Transform(word, trans_map); //打印输出 } cout << endl; } } //生成转换文本 int main(void) { ifstream map_file("rule.txt"); ifstream in_put("target.txt"); word_transform(map_file, in_put); return 0; } /**********************************************************************************************************************/