[STL]单词转换

时间:2023-03-09 08:40:35
[STL]单词转换

如果单词转换文件的内容是:

'em         them
cuz         because
gratz      grateful
i             I
nah        no
pos        supposed
sez        said
tanx      thanks
wuz       was

而要转换的文本是:

nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz

则程序将产生如下输出结果:

[STL]单词转换

代码如下:

 #include<iostream>
#include<map>
#include<string>
#include<fstream>
#include<sstream>
using namespace std; int main()
{
map<string,string> trans_map;
string key,value;
ifstream ifile("a.txt");//a.txt存放转换文件
if(!ifile)
throw runtime_error("no translation file");
while(ifile>>key>>value)
{
trans_map.insert(make_pair(key,value));
}
ifstream input("b.txt");//b.txt存放要转换的文件
if(!input)
throw runtime_error("no input file");
string line;
while(getline(input,line))//每次读一行
{
istringstream stream(line);//每次读一个单词
string word;
bool firstword=true;//首个单词前不需要空格
while(stream>>word)
{
map<string,string>::const_iterator map_it=trans_map.find(word);
if(map_it!=trans_map.end())//若map中存在就替换
{
word=map_it->second;
}
if(firstword)
{
firstword=false;
}
else
{
cout<<" ";
}
cout<<word;
}
cout<<endl;
}
return ;
}