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;
}
运行结果显示如下
相关推荐
甄同学1 分钟前
第十七篇:Bash Executor命令执行器,安全运行Shell命令
开发语言·安全·bash
张3232 分钟前
Go语言基础 Map 函数值 闭包
开发语言·golang
变量未定义~10 分钟前
单调栈-四元组问题
数据结构·算法
冷小鱼17 分钟前
AI Agent 核心算法:任务规划(Planning)的深度技术解析
人工智能·算法·planning
杜子不疼.22 分钟前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
退休倒计时25 分钟前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript
有点。26 分钟前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
旖-旎29 分钟前
《LeetCode 978 最长湍流子数组 || LeetCode 139 单词拆分》
c++·算法·leetcode·动态规划
时间的拾荒人32 分钟前
C语言编译与链接:从源码到可执行程序的完整解析
c语言·开发语言
人道领域33 分钟前
【0-1的agent进阶篇】Prompt 与上下文工程
java·开发语言·prompt·mcp