您的位置:首页 > 编程语言 > C语言/C++

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

2013-06-05 23:55 483 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: