C++ //练习 11.33 实现你自己版本的单词转换程序。

C++ Primer(第5版) 练习 11.33

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

环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp 复制代码
/*************************************************************************
	> File Name: ex11.33.cpp
	> Author: 
	> Mail: 
	> Created Time: Mon 08 Apr 2024 09:00:00 AM CST
 ************************************************************************/

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<map>
#include<iterator>
using namespace std;

map<string, string> buildMap(ifstream &map_file){
    map<string, string> map;
    string key;
    string value;
    while(map_file>>key && getline(map_file, value)){
        if(value.size() > 1){
            map[key] = value.substr(1);
        }
        else{
            throw runtime_error("no rule for " + key);
        }   
    }
    return map;
}

const string &transform(const string &s, const map<string, string> &m){
    auto it = m.find(s);
    if(it != m.cend()){
        return it->second;
    }
    else{
        return s;
    }
}

void txtTransform(ifstream &map_file, ifstream &input){
    auto map = buildMap(map_file);
    string txt;
    while(getline(input, txt)){
        istringstream stream(txt);
        string word;
        bool nonspace = true;
        while(stream>>word){
            if(nonspace){
                nonspace = false;
            }
            else{
                cout<<" ";
            }
            cout<<transform(word, map);
        }
        cout<<endl;
    }
}

int main(){
    ifstream map_file("map_file.txt");
    ifstream input("input.txt");
    txtTransform(map_file, input);

    return 0;
}
运行结果显示如下
相关推荐
WolfGang00732110 分钟前
代码随想录算法训练营 Day32 | 动态规划 part05
算法·动态规划
wjs202413 分钟前
JavaScript 条件语句
开发语言
阿里加多33 分钟前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
碧海银沙音频科技研究院35 分钟前
1-1杰理蓝牙SOC的UI配置开发方法
人工智能·深度学习·算法
2301_792674861 小时前
java学习day29(juc)
java·开发语言·学习
啊我不会诶1 小时前
2024CCPC长春邀请赛
算法
珂朵莉MM1 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--启发式算法+操作因子设计
人工智能·算法
周末也要写八哥1 小时前
MATLAB R2025a超详细下载与安装教程(附安装包)
开发语言·matlab
blog_wanghao2 小时前
基于Qt的串口调试助手
开发语言·qt
CS创新实验室2 小时前
CS实验室行业报告:AI算法工程师就业分析报告
人工智能·算法