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;
}
运行结果显示如下
相关推荐
珂朵莉MM几秒前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--碳中和
人工智能·算法
by__csdn1 分钟前
JavaScript性能优化实战:异步与延迟加载全方位攻略
开发语言·前端·javascript·vue.js·react.js·typescript·ecmascript
阿里嘎多学长2 分钟前
2025-12-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管
良木生香3 分钟前
【数据结构-初阶】详解线性表(2)---单链表
c语言·数据结构·算法
牛三金3 分钟前
魔改-隐语PSI通信,支持外部通信自定义
服务器·前端·算法
菜鸟233号3 分钟前
力扣106 从中序与后序遍历序列构造二叉树 java实现
java·算法·leetcode
水天需0104 分钟前
Linux 下查找 UID 的多种方法
c++
diudiu96287 分钟前
Logback使用指南
java·开发语言·spring boot·后端·spring·logback
Donald_wsn7 分钟前
牛客 栈和排序 C++
数据结构·c++·算法
程序喵大人9 分钟前
记录va_list重复使用导致的crash
开发语言·c++