C++自学笔记_单词转换map对象_《C++ Primer》

今天在干《C++ Primer》第10章的时候似乎遇到了一点小瓶颈,翻回第8章吃了顿回头草。所以,老话说得好:欠下的总是要还滴 :)

 

一个小程序,很简单:单词转换程序:程序输入两个文件,第一个文件包括了若干单词对,每对的第一个单词将出现在输入的字符串中,而第二个单词

则是用于输出。本质上,这个文件提供的是单词转化的集合——在遇到第一个单词时,应该将之替换为第二个单词。第二个文件则提供了需要转换的文本。

 

打个比方:如果单词转换文件的内容为:

 

 

而要转换的文本是:

 

Code:

#include <iostream>
#include <map>
#include <fstream>

using namespace std;

int main()
{
    string fileName1("F:\\file1.txt");       //file1
    string fileName2("F:\\file2.txt");       //file2
    string fileName3("F:\\file3.txt");       //file3
    map<string,string> trans_map;            //定义map对象,存储file1的内容
    string key,value;                        //键值对
    ifstream infile;                         //infile提供读文件操作,读file1.txt
    infile.open(fileName1.c_str());          //别忘了要把文件名转化为C风格字符串!
    if(!infile){
        cerr<<"error:enable open file:"<<fileName1<<endl;
        return 0;
    }else{
        cout<<"open file:"<<fileName1<<" success"<<endl;
    }
    while(infile>>key>>value){                //将file1中的键值对读出来存放在trans_map内
        trans_map.insert(make_pair(key,value));
    }
    infile.close();
    ifstream input;                           //input提供读文件操作,读file2.txt
    ofstream outfile;                         //outfile提供写文件操作,写入file3.txt
    input.open(fileName2.c_str());
    if(!input){
        cerr<<"error:enable open file:"<<fileName2<<endl;
        return 0;
    }else{
        cout<<"open file:"<<fileName2<<" success"<<endl;
    }
    outfile.open(fileName3.c_str());
    if(!outfile){
        cerr<<"error:enable open file:"<<fileName3<<endl;
        return 0;
    }else{
        cout<<"open file:"<<fileName3<<" success"<<endl;
    }
    string word;
    bool firstWord=true;                     //用来判断是否是第一个单词,用来处理空格的输出
    while(input>>word){                      //读单词(string)
        map<string,string>::const_iterator iter=trans_map.find(word);   //如果word存在,返回指向word的迭代器
        if(iter!=trans_map.end()){
            word=iter->second;               //迭代器是指向一个存在的元素,把word修改为file1.txt规定的对应的单词
            cout<<word<<endl;                //这个是输出在Console上看了玩的
        }
        if(firstWord){                       //第1个单词的情况
            firstWord=false;
            outfile<<word;
        }
        else{
            outfile<<" "<<word;              //从第2个开始就要在每个单词前面输出一个空格了
        }
        input.clear();
        outfile.clear();
    }
    outfile<<endl;
    return 0;
}

鲁棒性有待商榷,还需要多次优化。

 

程序将在一个文本文件写入结果:

 

睡一觉再动手 :)

转载于:https://www.cnblogs.com/Murcielago/p/4160811.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值