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;
}
运行结果显示如下
相关推荐
优化控制仿真模型8 分钟前
2026年最新驾考科目一考试题库2309道全。电子版pdf
经验分享·算法·pdf
python猿10 分钟前
打卡Python王者归来--第30天
开发语言·python
qq_3349031510 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
阿贵---22 分钟前
C++代码规范化工具
开发语言·c++·算法
暮冬-  Gentle°30 分钟前
自定义内存检测工具
开发语言·c++·算法
一直都在57230 分钟前
Java死锁
java·开发语言
娇娇yyyyyy32 分钟前
QT编程(15): Qt 按键事件和定时器事件
开发语言·qt
ccLianLian41 分钟前
数论·欧拉函数
数据结构·算法
2501_945424801 小时前
C++编译期矩阵运算
开发语言·c++·算法
yy我不解释1 小时前
关于comfyui的mmaudio音频生成插件时时间不一致问题(三)
开发语言·python·ai作画·音视频·comfyui