c++ primer 5th ed. practice 11.33

本文介绍了一个使用C++编写的单词转换程序,通过读取外部映射文件,实现在输入文本中应用预定义的单词替换规则,适用于文本处理和本地化需求。

实现你自己版本的单词转换程序。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>

void word_transform(std::ofstream &output,								//添加输出流
                    std::ifstream &input, std::ifstream &map_file); 	//待译文件流 及 译本流
std::map<std::string, std::string> build_map(std::ifstream &map_file);
const std::string& transform(const std::string &s,
                            const std::map<std::string, std::string> &m);

int main() {

    std::ifstream map_file("map_file.dat"), input("input.dat");
    //std::ofstream output("output.dat", std::ofstream::app);				//追加文件
    std::ofstream output("output.dat");

    word_transform(output, input, map_file);

    std::cout << "Done." << std::endl;
}

//文本转换并输出
void word_transform(std::ofstream &output, 
                    std::ifstream &input, std::ifstream &map_file) {
        
    auto trans_map = build_map(map_file);
    std::string text;
    while (std::getline(input, text)) {

        std::istringstream stream(text);
        std::string word;
        bool firstword = true;
        while (stream >> word) {
        //单词前缀空格添加
            if (firstword)
                firstword = false; //跳过第一个单词
            else 
                output << " ";
            output << transform(word, trans_map);
        }   
        output << std::endl;
    }   
}
//转换映射
std::map<std::string, std::string> build_map(std::ifstream &map_file) {
        
    std::map<std::string, std::string> trans_map;
    std::string key, value;
    while (map_file >> key && std::getline(map_file, value))
        if (value.size() > 1)
            trans_map[key] = value.substr(1);
        //else
        //  throw std::runtime_error("no rule for" + key);
    return trans_map;
}
//转换操作
const std::string& transform(const std::string &s,
                            const std::map<std::string, std::string> &m) {

    auto map_it = m.find(s);
    if (map_it != m.end())
        return map_it->second;
    else
        return s;
}

添加空格小技巧 把空格设定为单词前缀,跳过第一个单词

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值