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

C++ string和map容器实现简单的英文翻译

2013-11-29 21:45 573 查看


int main(int argc, const char *argv[])
{
ifstream ifl;
ifl.close();
ifl.clear();

string mapfilename("map.txt");
string transformname("transform.txt");

ifl.open(mapfilename.c_str());

string key,value;
map<string,string> maptransform;
while(ifl>>key>>value)
{
maptransform.insert(make_pair(key,value));
}
ifl.close();
ifl.clear();

ostream::fmtflags oldflags=cout.flags();

map<string,string>::iterator iter=maptransform.begin();

cout<<"---------------------------------------"<<endl;
cout<<"the map.txt is: "<<endl;
while(iter!=maptransform.end())
{
string tmp;
cout<<setw(16)<<left;
(tmp="key: ")+=iter->first;
cout<<tmp;
cout<<setw(16)<<left;
(tmp="value: ")+=iter->second;
cout<<tmp<<endl;
++iter;
}

cout.flags(oldflags);

cout<<"---------------------------------------"<<endl;
ifl.open(transformname.c_str());
string tmp,text;
cout<<"the transformname.txt is: "<<endl;
while(getline(ifl,tmp))
{
cout<<tmp<<endl;
text+=tmp+='\n';
}

{
string subtext(text);
cout<<"transform transform.txt`s text by string::find "
<<"and string::replace : "<<endl;

for(iter=maptransform.begin();iter!=maptransform.end();++iter)
{
string::size_type pos=subtext.find(iter->first);
if(pos!=string::npos)
subtext.replace(pos,iter->first.size(),iter->second);
}
cout<<subtext;
}

{

cout<<"---------------------------------------"<<endl;
cout<<"transform transform.txt`s text "
<<"by instead ostream : "<<endl;
istringstream istm(text);
string word;
bool firstword=true;
while(istm>>word)
{
map<string,string>::const_iterator iter=
maptransform.find(word);
if(iter!=maptransform.end())
word=iter->second;
cout<<(firstword?(firstword=false,""):" ")<<word;
}
cout<<endl;
}

ifl.close();
ifl.clear();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: