C++ //练习 11.33 实现你自己版本的单词转换程序。

C++ Primer(第5版) 练习 11.33

练习 11.33 实现你自己版本的单词转换程序。

环境:Linux Ubuntu(云服务器)
工具:vim

 

代码块
/*************************************************************************
	> 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;
}
运行结果显示如下

在这里插入图片描述

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-10 06:22:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-10 06:22:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-10 06:22:04       82 阅读
  4. Python语言-面向对象

    2024-04-10 06:22:04       91 阅读

热门阅读

  1. python中os模块和sys模块的使用

    2024-04-10 06:22:04       35 阅读
  2. DOTS Unity.Physics物理引擎碰撞事件处理

    2024-04-10 06:22:04       34 阅读
  3. HTML5本地存储(localStorage和sessionStorage)

    2024-04-10 06:22:04       38 阅读
  4. ubuntu 18.04 安装 OpenSSL libssl.so.1.1

    2024-04-10 06:22:04       34 阅读