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;
}
运行结果显示如下
相关推荐
蚂蚁数据AntData7 分钟前
破解AI“机器味“困境:HeartBench评测实践详解
大数据·人工智能·算法·机器学习·语言模型·开源
ZC跨境爬虫9 分钟前
Python异步IO详解:原理、应用场景与实战指南(高并发爬虫首选)
爬虫·python·算法·自动化
不想写代码的星星13 分钟前
C++ 内存管理:分区、自定义分配器、常见问题与检测工具
c++
前进的李工15 分钟前
MySQL大小写规则与存储引擎详解
开发语言·数据库·sql·mysql·存储引擎
倦王21 分钟前
力扣日刷47-补
python·算法·leetcode
错把套路当深情32 分钟前
Java 全方向开发技术栈指南
java·开发语言
前端郭德纲33 分钟前
JavaScript Object.freeze() 详解
开发语言·javascript·ecmascript
-许平安-44 分钟前
MCP项目笔记九(插件 bacio-quote)
c++·笔记·ai·plugin·mcp
沉鱼.441 小时前
第十三届题目
c语言·c++·算法
ZHOU_WUYI1 小时前
ppo算法简单实现
人工智能·pytorch·算法