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

5 篇文章 0 订阅



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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值