二、单词转换器(转换译码)
代码有点丑,输入输出IO库还很需要加强。。。对文件的操作基本是文盲。。
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
// 2013.11.18 Written by C_SuooL_Hu
using namespace std;
ifstream& open_file(ifstream&, const string&);
int main()
{
 freopen("out.txt", "w", stdout);
 // map to hold the word transformation pairs: 
 // key is the word to look for in the input; value is word to use in the output
 map<string, string> trans_map;
    string key, value;
 
 // ´´½¨Á÷
 ifstream myfile ("trans_map.txt");
 ifstream myfilein ("in.txt");
 ofstream outfile("out.txt");
 // ÅжÏÎļþÊÇ·ñ´ò¿ª
 if(!myfile)
 {
  cout << "Unable to open myfile";
        exit(1); // terminate with error
  
 }
 if(!outfile)
 {
  cout << "Unable to open outfile";
        exit(1); // terminate with error
  
 }
 
    // read the transformation map and build the map 
    while (myfile >> key >> value) 
 {
  trans_map.insert(make_pair(key, value));
 }
 
 // this block just produces the vector so that we can print it
 // for the book
 cout << "Here is our transform string input:\n\n";
 // read some text to transform
 string word;
 
    // ok, now we're ready to do the transformations
    // open the input file and check that the open succeeded
 string WORD;
 bool firstword = true;  // controls whether a space is printed 
 while (myfilein >> WORD) 
 {
  // ok: the actual mapwork, this part is the heart of the program
  map<string, string>::const_iterator map_it =
   trans_map.find(WORD);
  
  // if this word is in the transformation map
  if (map_it != trans_map.end()) 
  {
   // replace it by the transformation value in the map
   WORD = map_it->second;  
  }
  if (firstword)
   firstword = false;
  else
   cout << " ";  // print space between words
  cout << WORD;
 }
 cout << endl;        // done with this line of input
    return 0;
}
测试结果:

