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;
}
运行结果显示如下
相关推荐
lsx2024062 分钟前
NumPy 创建数组
开发语言
Han.miracle15 分钟前
Java集合核心:ArrayList与LinkedList深度解析
java·开发语言
@淡 定28 分钟前
DDD领域事件详解:抽奖系统实战
开发语言·javascript·网络
@卞36 分钟前
从零实现一个高并发内存池(1)--- 项目介绍
c++
lly20240638 分钟前
DOM 简介
开发语言
期待のcode38 分钟前
Java的反射
java·开发语言
j .39 分钟前
Java 集合的核心概念笔记
开发语言·python
wjlnew1 小时前
c++中的内存管理:栈,堆及RALL机制
c++
2201_757830871 小时前
AOP入门程序
java·开发语言
笃行客从不躺平1 小时前
ThreadLocal 复习一
java·开发语言