c++Primer 关联容器单词转换例子
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
std::map<std::string, std::string> build_map(std::ifstream& rule_file); // 读取规则文件
const std::string& transform(const std::string& word, const std::map<std::string, std::string>& mp); // 对每一个单词进行转换
// 注意ifstream 对象不支持拷贝 也不能是const & 因为从ifstream中读取文件需要修改到ifstream
void word_transform(std::ifstream& rule, std::ifstream& input)
{
auto rule_map = build_map(rule);
std::string line;
while (std::getline(input, line)) {
std::istringstream iss(line); // 初始化一个istringsstream对象
std::string word;
bool is_first_word = true;
while (iss >> word) { // 输入流对象遇到空格等空字符会停止本次输入返回 全部输入完后返回false
if (is_first_word) {
is_first_word = false;
}
else {
std::cout << " ";
}
std::cout << transform(word, rule_map);
}
std::cout << std::endl;
}
}
std::map<std::string, std::string> build_map(std::ifstream& rule_file)
{
std::string line;
std::string key;
std::string value;
// 输入流对象遇到空格将会停止输入并返回true 此时文件流指针移动到空格处 再用getline从该处一直读到遇到换行
// eg : "brb be right back" 中key会读进去brb 文件流指针指向第一个空格处 value将会读取到" be right back"
std::map<std::string, std::string> mp;
while (rule_file >> key && std::getline(rule_file, value)) {
// 此时value将以空格开头 要去掉这个空格
if (value.size() > 1) {
mp[key] = value.substr(1);
}
else {
std::string err = "no rule for : ";
throw std::runtime_error(err + key);
}
}
return mp;
}
const std::string& transform(const std::string& word, const std::map<std::string, std::string>& mp)
{
auto it = mp.find(word);
if (it != mp.end()) {
return it->second;
}
else {
return word;
}
}
int main()
{
std::ifstream input_file("./input.txt", std::ios::out);
std::ifstream rule_file("./rule.txt", std::ios::out);
if (input_file.good() && rule_file.good()) {
word_transform(rule_file, input_file);
}
else {
std::cout << "read file error" << std::endl;
}
return 0;
}
input.txt:
where r u
y dont u send me a pic
k thk l8r
rule.txt:
brb be right back
k okay?
y why
r are
u you
pic picture
thk thanks!
l8r later