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

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值