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;
}
运行结果显示如下
相关推荐
leaves falling10 分钟前
C++模板进阶
开发语言·c++
无敌昊哥战神26 分钟前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__28 分钟前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode
再卷也是菜28 分钟前
算法提高篇(1)线段树(上)
数据结构·算法
py有趣31 分钟前
力扣热门100题之单词拆分
算法·leetcode
ouliten36 分钟前
C++笔记:std::invoke
c++·笔记
坐吃山猪40 分钟前
Python27_协程游戏理解
开发语言·python·游戏
gCode Teacher 格码致知41 分钟前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript
椰猫子1 小时前
Javaweb(Filter、Listener、AJAX、JSON)
java·开发语言
j_xxx404_2 小时前
C++算法:哈希表(简介|两数之和|判断是否互为字符重排)
数据结构·c++·算法·leetcode·蓝桥杯·力扣·散列表