#include<iostream> #include<string> #include<map> #include<fstream> #include<sstream> using namespace std; map<string,string> buildMap(ifstream &map_file); const string &transform(const string &s,const map<string,string> &m); void word_transform(ifstream &map_file,ifstream &input) { auto trans_map=buildMap(map_file);//保存转换规则 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; //完成一行的转换 } } map<string,string> buildMap(ifstream &map_file) { map<string,string> trans_map; //保存转换规则 string key; //要转换的单词 string value; //替换后的内容 while(map_file>>key&&getline(map_file,value))//读取第一个单词存入key中,行中剩余内容存入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<string,string> &m) { auto map_it=m.find(s); //实际转换规则 if(map_it!=m.cend()) //如果单词在转换规则map中 return map_it->second; //使用替换短语 else return s; //否则返回原string } int main() { ifstream in1("1.txt"); ifstream in2("2.txt"); word_transform(in1,in2); return 0; }
k okay? y why r are u you pic picture thk thanks! l8r later
以上是1.txt
where r u y dont u send me a pic k thk l8r
以上是2.txt