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;
}
运行结果显示如下
相关推荐
一个不知名程序员www2 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
二哈喇子!3 小时前
BOM模型
开发语言·前端·javascript·bom
C++ 老炮儿的技术栈3 小时前
在C++ 程序中调用被 C编译器编译后的函数,为什么要加 extern “C”声明?
c语言·c++·windows·git·vscode·visual studio
二哈喇子!3 小时前
空指针异常
开发语言
咚为3 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
%xiao Q3 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang3 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Traced back3 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
Sarvartha3 小时前
C++ STL 栈的便捷使用
c++·算法
sin22013 小时前
MyBatis的执行流程
java·开发语言·mybatis