c++学习笔记——个单词转换的map程序详解

时间:2023-03-10 08:40:22
c++学习笔记——个单词转换的map程序详解

实现功能:给定一个string,将它转换为另一个string。程序输入是两个文件,第一个文件保存转换规则,第二个文件为将要进行转换的文本。

IDE:Windows7+VS2013

  1. #include "stdafx.h"
  2. #include <map>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <string>
  6. #include <stdexcept>
  7. #include <sstream>
  8. using namespace std;
  9. map<string, string> buildMap(ifstream &map_file)     //读入给定rules.text文件,建立转换映射
  10. {
  11. map<string, string> trans_map;   //保存转换规则
  12. string key;                      //要转换的单词
  13. string value;                   //替换后的内容
  14. //读取第一个单词存入key中,行中剩余内容存入value
  15. while (map_file >> key && getline(map_file, value))
  16. if (value.size() > 1)        //检查是否有转换规则
  17. trans_map[key] = value.substr(1);
  18. else
  19. throw runtime_error("no rule for " + key);
  20. return trans_map;
  21. }
  22. const string &transform(const string &s, const map<string, string> &m)
  23. {
  24. auto map_it = m.find(s);
  25. if (map_it != m.cend())        //如果单词在转换规则m中
  26. return map_it->second;     //使用替换短语
  27. else
  28. return s;                  //否则返回原string
  29. }
  30. void word_transform(ifstream &map_file, ifstream &input)
  31. {
  32. auto trans_map = buildMap(map_file);   //保存转换规则
  33. cout << "转换规则为: \n";
  34. for (auto entry : trans_map)
  35. cout << "key: " << entry.first<< "\tvalue: " << entry.second << endl;
  36. cout << "\n\n";
  37. string text;                     //保存输入中的每一行
  38. cout << "转换后为: \n";
  39. while (getline(input, text))
  40. {
  41. istringstream stream(text); //读取每一个单词
  42. string word;
  43. bool firstword = true;     //控制是否打印空格
  44. while (stream >> word)
  45. {
  46. if (firstword)
  47. firstword = false;
  48. else
  49. cout << " ";
  50. cout << transform(word, trans_map);
  51. }
  52. cout << endl;
  53. }
  54. }
  55. int _tmain(int argc, _TCHAR* argv[])
  56. {
  57. if (argc != 3)
  58. throw runtime_error("wrong number of arguments");
  59. ifstream map_file(argv[1]);    //第一个参数为rules.text文件
  60. if (!map_file)
  61. throw runtime_error("no transformation file");
  62. ifstream input(argv[2]);      //第二个参数为text.text文件
  63. if (!input)
  64. throw runtime_error("no input file");
  65. word_transform(map_file, input);
  66. return 0;
  67. }

将rules.text和text.text文件放在E盘根目录下

c++学习笔记——个单词转换的map程序详解

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

c++学习笔记——个单词转换的map程序详解

调试运行,结果如图示

c++学习笔记——个单词转换的map程序详解