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;
}
运行结果显示如下
相关推荐
(Charon)27 分钟前
【C++面试】vector底层原理:扩容、拷贝移动与迭代器失效
c++·面试
zhangzeyuaaa38 分钟前
深入理解 Ruby 运算符:本质、分类、坑点与重载实战
开发语言·前端·ruby
一木 之林42 分钟前
DeepSeek Agent 开发(一)
开发语言·前端·javascript
朔北之忘 Clancy43 分钟前
青少年软编等考七级题解目录
开发语言·c++·青少年编程·gesp·csp·信奥赛·noi
ss2731 小时前
AI全栈实战 | 3.2-01 Python 基础:四大数据容器怎么选,推导式为什么是 Pythonic 的灵魂
开发语言·人工智能·python
汉克老师1 小时前
GESP2026年9月认证C++七级( 第一部分选择题(8~15题)精讲
c++·gesp·小学生·学c++编程
Mr_Macallon1 小时前
C++回顾(基础)(01)
c语言·开发语言·c++·学习
未来之窗软件服务1 小时前
Go 利器 GoReSym:剥离符号恢复 Go 二进制元数据—东方仙盟
开发语言·golang·仙盟创梦ide·东方仙盟
垆边人似月.1 小时前
任务混部(200 分档)
算法
言乐61 小时前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先