1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
//读取对照表,存为字典
map<string,string> buildMap(ifstream &map_file){
map<string,string> trans_map;
string key,value;
while(map_file>>key && getline(map_file,value)) //利用&&的执行顺序,先读一个单词,再取剩下的一行
if(value.size()>1) //若转换规则存在
trans_map[key]=value.substr(1); //取子串,忽略getline读到的第一个空格
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()) //不等于end则查找到
return map_it->second;
else
return s;
}
//读取对照表和输入,打印输出
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;
}
}
|