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;
}
运行结果显示如下
相关推荐
MMjeaty几秒前
查找及其算法
c++·算法
青光键主1 分钟前
C语言内功强化之const修饰指针
c语言·开发语言
骷大人27 分钟前
php安装skywalking_agent
开发语言·php·skywalking
寂静山林35 分钟前
UVa 1597 Searching the Web
数据结构·算法
云泽80840 分钟前
排序算法实战:从插入排序到希尔排序的实现与性能对决
算法·排序算法
多恩Stone1 小时前
【3DV 进阶-5】3D生成中 Inductive Bias (归纳偏置)的技术路线图
人工智能·python·算法·3d·aigc
恋恋西风1 小时前
Qt 打开文件列表选择文件,实现拖拽方式打开文件,拖拽加载
开发语言·qt
yong15858553431 小时前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
闲人编程1 小时前
使用Python进行量化交易入门
开发语言·python·统计分析·lambda·量化·codecapsule
.ZGR.2 小时前
蓝桥杯高校新生编程赛第二场题解——Java
java·算法·蓝桥杯