C++ primer ————————————“单词转换" map 对象

来源:互联网 发布:悠游域名抢注工具 编辑:程序博客网 时间:2024/05/18 01:54
#include<iostream>#include<map>#include<string>#include<utility>#include<fstream>#include<sstream>/*单词转换:给出一个string 对象 转换成另一个string对象 :输入是两个文件 第一个 含有若干单词对 做词典功能: 第二个文件 提供了需要转换的文件。 */using namespace std;typedef pair<string,string> str_str;int main(){    map<string,string> trans_map;   // 存放转换文件的内容   string key,value,word;   string filename;      char str[256];                 //  存放从行中得到的数据      ifstream map_file;              // 第一个文件   cout <<"Input the map file..."<< endl;   cin >> filename;   map_file.open(filename.c_str(),ios:: in);    if(!map_file.is_open())                    //鲁棒性   {      cout <<"file cannot be open"<<endl;        exit(1);             }   while(!map_file.eof())   {   map_file.getline(str,256,'\n');       istringstream str_stream(str);        str_stream >> key;        str_stream >> value;   trans_map.insert(str_str(key,value));      }   ifstream file;   cout <<"Input the file:"<<endl;   cin >> filename;   file.open(filename.c_str(),ios::in);      if(!file.is_open())                    //鲁棒性   {      cout <<"file cannot be open"<<endl;        exit(1);             }      while(!file.eof())   { file.getline(str,256,'\n'); string word;     istringstream str_stream(str);     bool firstword = true;     while(str_stream >> word)          {       map<string,string>::iterator  it = trans_map.find(word);       if(it != trans_map.end())       word = it->second;        if(firstword)       firstword = false;       else       cout << " ";       cout << word;              }        cout << endl;   }     system("pause");   return 0;}

原创粉丝点击