/*
本程序输入是两个文件,第一个文件(命名为1.txt)包括了若干单词对,每对的第一个单词将出现在输入的字符串中,
而第二个单词是用于输出,本质上,这个文件提供的是单词转换的集合--在遇到第一个单词时,应该将之
替换为第二个单词。第二个文件(2.txt)提供需要转换的文本。
*/
#include<string>
#include<map>
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
ifstream& open_file(ifstream &in, const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
int main(int argc, char *argv[])
{
//trans_map中存放转换对,key 是在input中找到的单词,value指的是要输出的单词。
map <string, string> trans_map;
string key, value;
if(argc != 3)
throw runtime_error("no transformation file");
ifstream map_file;
if(!open_file(map_file,argv[1]))
throw runtime_error("no transformation file");
while(map_file >> key >> value)
trans_map.insert(make_pair(key, value));
ifstream input;
if(!open_file(input, argv[2]))
throw runtime_error("no input file");
string line;
while(getline(input, line))// 将input中的每一行读入到line中。
{
istringstream stream(line);
string word;
bool firstword = true;
while(stream >> word)
{
map<string , string>::const_iterator map_it = trans_map.find(word);
if(map_it != trans_map.end())
word = map_it->second;
if(firstword)
firstword = false;
else
cout << " ";
cout << word;
}
cout << endl;
}
return 0;
}
输入输出为:
其中:
另外注意下面在文件中的位置: