实现你自己版本的单词转换程序。
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
void word_transform(std::ofstream &output, //添加输出流
std::ifstream &input, std::ifstream &map_file); //待译文件流 及 译本流
std::map<std::string, std::string> build_map(std::ifstream &map_file);
const std::string& transform(const std::string &s,
const std::map<std::string, std::string> &m);
int main() {
std::ifstream map_file("map_file.dat"), input("input.dat");
//std::ofstream output("output.dat", std::ofstream::app); //追加文件
std::ofstream output("output.dat");
word_transform(output, input, map_file);
std::cout << "Done." << std::endl;
}
//文本转换并输出
void word_transform(std::ofstream &output,
std::ifstream &input, std::ifstream &map_file) {
auto trans_map = build_map(map_file);
std::string text;
while (std::getline(input, text)) {
std::istringstream stream(text);
std::string word;
bool firstword = true;
while (stream >> word) {
//单词前缀空格添加
if (firstword)
firstword = false; //跳过第一个单词
else
output << " ";
output << transform(word, trans_map);
}
output << std::endl;
}
}
//转换映射
std::map<std::string, std::string> build_map(std::ifstream &map_file) {
std::map<std::string, std::string> trans_map;
std::string key, value;
while (map_file >> key && std::getline(map_file, value))
if (value.size() > 1)
trans_map[key] = value.substr(1);
//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.end())
return map_it->second;
else
return s;
}
添加空格小技巧 把空格设定为单词前缀,跳过第一个单词
本文介绍了一个使用C++编写的单词转换程序,通过读取外部映射文件,实现在输入文本中应用预定义的单词替换规则,适用于文本处理和本地化需求。

被折叠的 条评论
为什么被折叠?



