#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;
}
C++ primer ————————————“單詞轉換" map 對象
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.