C++ primer 第十一章 使用map完成 单词转换程序 一体式笔记(含大量注释)

#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<map>


//建立转换映射
std::map<std::string, std::string> bulidMap(std::ifstream &);
//生成转换文本
const std::string&
transform(const std::string&, const std::map<std::string, std::string>&);

//主体函数
void word_transform(std::ifstream& map_file, std::ifstream& input) {
	auto trans_map = bulidMap(map_file);	//保存转换规则
	std::string text;						//保存输入的每一行
	while (getline(input, text)) {			//读取每一行输入
		std::istringstream stream(text);	//读取每个单词	/*调用sstream的构造函数,创建stream对象保存text的一个拷贝*/
		std::string word;
		bool fristword = true;				//控制是否打印空格
		while (stream >> word) {
			if (fristword)
				fristword = false;
			else
				std::cout << " ";			//单词之间打印空格
			//转换并打印输出
			std::cout << transform(word, trans_map);
		}
		std::cout << std::endl;				//完成一行的输入
	}
}

//转换映射函数的实现
std::map<std::string, std::string> bulidMap(std::ifstream& map_file) {
	std::map<std::string, std::string> trans_map;
	std::string key;
	std::string value;
	//读取第一个单词存入key中,行内剩余内容存入value
	while (map_file >> key && getline(map_file, value)) {	
		if (value.size() > 1) {					//getline不会跳过前导空格
			trans_map[key] = value.substr(1);	//跳过前导空格
		}										//s.substr(pos,n),返回包含从pos开始的n个字符的拷贝的string,n的默认值是s.size()-pos
		else {
			throw std::runtime_error("no rule for " + key);	//抛出异常
		}
	}
	return trans_map;
}
//生成文本函数的实现
const std::string&
transform(const std::string& s, const std::map<std::string, std::string>& m) {
	auto map_it = m.find(s);	//返回迭代器
	if (map_it != m.cend())
		return map_it->second;
	else
		return s;
}


文件流初始化方式icon-default.png?t=N7T8https://blog.csdn.net/c_base_jin/article/details/79360909

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值