/*
本程序輸入是兩個文件,第一個文件(命名爲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;
}
輸入輸出爲:
其中:
另外注意下面在文件中的位置: