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 小时前
Python 2025:AI工程化与智能代理开发实战
开发语言·人工智能·python
会开花的二叉树2 小时前
彻底搞懂 Linux 基础 IO:从文件操作到缓冲区,打通底层逻辑
linux·服务器·c++·后端
在下雨5993 小时前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
再努力"亿"点点3 小时前
Sklearn(机器学习)实战:鸢尾花数据集处理技巧
开发语言·python
清朝牢弟3 小时前
Win系统下配置PCL库第一步之下载Visual Studio和Qt 5.15.2(超详细)
c++·qt·visual studio
Jayyih3 小时前
嵌入式系统学习Day36(简单的网页制作)
学习·算法
深耕AI3 小时前
【MFC视图和窗口基础:文档/视图的“双胞胎”魔法 + 单文档程序】
c++·mfc
饭碗的彼岸one3 小时前
C++ 并发编程:异步任务
c语言·开发语言·c++·后端·c·异步
脑洞代码3 小时前
20250909的学习笔记
算法
Christo33 小时前
TFS-2003《A Contribution to Convergence Theory of Fuzzy c-Means and Derivatives》
人工智能·算法·机器学习