C++ Primer 第十章 10.3.9 “单词转换”map对象

来源:互联网 发布:淘宝客网站app制作 编辑:程序博客网 时间:2024/06/06 14:28
题目:给出一个string对象,把它转换为另一个string对象。本程序的输入是两个文件。第一个文件包括了若干单词对,每对的第一个单词将出现在输入的字符串中,而第二个单词则是用于输出。本质上,这个文件提供的是单词转换的集合--遇到第一个单词时,应该将之替换为第二个单词。第二个文件则提供了需要转换的文本。
如果单词转换文本的内容是:
'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
那么:程序将产生如下输出结果:
no I said thanks because I was supposed to

not because I was grateful



源代码


#include<iostream>
#include<fstream>
#include<map>
#include<string>
#include<sstream>
#include<vector>
#include<exception>
#include<stdexcept>
using namespace std;


ifstream& open_file(ifstream &in,const string &file)
{
    in.close();
    in.clear();
    in.open(file.c_str());
    
    return in;
}


int main(int argc,char **argv)
{
    map<string,string> trans_map;
    string key,value;


    if(argc!=3)
{
        throw runtime_error("wrong number of arguments");
    }


    ifstream map_file;
    if(!open_file(map_file,argv[1]))    
{
        throw runtime_error("no transformation file");
    }
    while(map_file>>key>>value)
{
 trans_map.insert(make_pair(key,value));
}
   
    ifstream input;


    if(!open_file(input,argv[2]))    
    {
        throw runtime_error("no input file");
    }


    string line;


    while(getline(input,line))
    {
        istringstream stream(line);//read a word at a time
        string word;
        bool firsetword=true;//control whether a space is printed
        
        while(stream>>word)
        {
            map<string, string>::const_iterator  map_it=trans_map.find(word) ;


            if (map_it!=trans_map.end())
            {
                /* code */
                word=map_it->second;
            }


            if (firsetword)
            {
                /* code */
                firsetword=false;
            }
            else
            {
                cout<<" ";
            }


            cout<<word;
        }


        cout<<endl;
    }
    


    return 0;


}

1/

 g++ -o hehe tran_map.cc 

2/

./hehe "hello1.txt" "wanttoreplace.txt"


3/

hello1.txt

asd su
fgh min
jkl zhang
qwe xiao
rty qiu
uio hong
i   I


4/

wanttoraplace.txt

asd fgh jkl love qwe rty uio


5/

输出

su min zhang love xiao qiu hong

























0 0
原创粉丝点击