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;
}
运行结果显示如下
相关推荐
码匠许师傅2 分钟前
【C++ 面试真题】24. 聊聊 C++ 的时间日期处理
java·c++·面试
wenyq74 分钟前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
闻道且行之13 分钟前
图片处理助手|泊松融合原理 + C++ 工程实现,seamlessClone 三模式一次讲透
数据库·c++·人工智能·opencv
学习星球41 分钟前
Solid.js 实战:拆解官方 RealWorld 项目
开发语言·javascript·vue.js
OPEN-F41 分钟前
Python进阶教程:正则表达式进阶与文本处理
开发语言·python·正则表达式
.格子衫.1 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
zhifou1234561 小时前
java 17升级安装
java·开发语言
莫浅子1 小时前
day01-USB架构与枚举
c++·单片机·嵌入式驱动
for_ever_love__1 小时前
python基础语法学习: 面向对象的三大特性
开发语言·python·学习
不会代码的小猴2 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json