实现功能:给定一个string,将它转换为另一个string。程序输入是两个文件,第一个文件保存转换规则,第二个文件为将要进行转换的文本。
IDE:Windows7+VS2013
- #include "stdafx.h"
- #include <map>
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <stdexcept>
- #include <sstream>
- using namespace std;
-
- map<string, string> buildMap(ifstream &map_file)
- {
- map<string, string> trans_map;
- string key;
- string value;
-
- while (map_file >> key && getline(map_file, value))
- if (value.size() > 1)
- trans_map[key] = value.substr(1);
- else
- throw runtime_error("no rule for " + key);
- return trans_map;
- }
- const string &transform(const string &s, const map<string, string> &m)
- {
- auto map_it = m.find(s);
-
- if (map_it != m.cend())
- return map_it->second;
- else
- return s;
- }
- void word_transform(ifstream &map_file, ifstream &input)
- {
- auto trans_map = buildMap(map_file);
- cout << "转换规则为: \n";
- for (auto entry : trans_map)
- cout << "key: " << entry.first<< "\tvalue: " << entry.second << endl;
- cout << "\n\n";
- string text;
- cout << "转换后为: \n";
- while (getline(input, text))
- {
- istringstream stream(text);
- string word;
- bool firstword = true;
- while (stream >> word)
- {
- if (firstword)
- firstword = false;
- else
- cout << " ";
- cout << transform(word, trans_map);
- }
- cout << endl;
- }
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- if (argc != 3)
- throw runtime_error("wrong number of arguments");
- ifstream map_file(argv[1]);
- if (!map_file)
- throw runtime_error("no transformation file");
- ifstream input(argv[2]);
- if (!input)
- throw runtime_error("no input file");
- word_transform(map_file, input);
- return 0;
- }
将rules.text和text.text文件放在E盘根目录下

设置运行时参数,在项目属性里面,配置属性->调试->命令参数里面写上你的参数

调试运行,结果如图示

c++学习笔记——个单词转换的map程序详解
原文:http://www.cnblogs.com/xujian2014/p/4222582.html