#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
#include<map>
using namespace std;
map<string, string> Buildmap(istream& file) {
map<string, string>map1;
string key,value;
while (file >> key && getline(file, value))
if (value.size() > 1)
map1[key] = value.substr(1);
return map1;}
const string& transform(const string& s,const map<string, string>& m) {
auto it = m.find(s);
if (it != m.end())
return it->second;
else
return s;
}
void Change(ifstream& input, ifstream& rule,ofstream&n) {
map<string,string>map1=Buildmap(rule);
string text;
while (getline(input, text)) {
istringstream stream(text);
string word;
while (stream >> word) {
n << transform(word, map1) << ends;
}
n<< endl; }}
int main() {
ifstream infile("1.txt");
ifstream rule("2.txt");
ofstream out("3.txt");
Change(infile, rule,out);
return 0;
}
- Change()中巧妙的地方
本例中Change()中对于流输入的很巧妙,先getline()获得一行的输入,然后使用istringstream 将这一行一个个string元素进行处理。
- Buildmap() 中处理转换的规则
while (file >> key && getline(file, value))
if (value.size() > 1)
map1[key] = value.substr(1);
这里要正确理解缓冲区的工作原理,在file>>key
时缓冲区的第一个元素已经被传递了给key
,之后getline()所获取的元素为第一个元素之后的所有元素。
substr(n)
的作用是跳过开头的n个字符(包括空格)。