最近看到有关容器与流处理的部分内容,看到书上关于一段单词转化的代码,看上去感觉比较乱==b,按着自己的思路再写一遍:-)
该程序会在你电脑的D盘生成(或者你自己写一个)密码表的password list.txt文件,写入乱码和解密后的正确字符串;然后同样是在D盘找到需要解密的input.txt文件对里面的文档进行转换.
1 #include <iostream>
2 #include <fstream>
3 #include <sstream>
4 #include <map>
5 #include <string>
6
7 using namespace std;
8
9 int main()
10 {
11 try
12 {
13 map<string,string> trans_map;
14 string key,value;
15 char isContinue = 'y',BuildList = 'a';
16 fstream map_file;
17 cout<<"Already have a password list(a) or want to bulid a new one(b)?\n";
18 cin>>BuildList;
19 if(BuildList == 'b')
20 {
21 cout<<"Please build and input the password list: \n";
22 map_file.open("d:\\password list.txt",ios::out);
23 if(!map_file)
24 throw std::runtime_error("Password list_File cannot be opened!");
25 /*创建密码表**************************/
26 while(isContinue == 'y')
27 {
28 cin>>key>>value;
29 map_file<<key<<" "<<value<<'\n';
30 trans_map.insert(make_pair(key,value));
31 cout<<"Continue?(y/n)\n";
32 cin>>isContinue;
33 }
34 map_file.close();
35 }
36 cout<<"Password list is successfully builded!"<<endl;
37 map_file.open("d:\\password list.txt",ios::in);
38 if(!map_file)
39 throw std::runtime_error("Password list_File cannot be opened!");
40 /*读密码表数据并写入关联容器*************/
41 while(map_file>>key>>value)
42 {
43 trans_map.insert(make_pair(key,value));
44 }
45 map_file.close();
46 fstream input_file;
47 input_file.open("d:\\input.txt",ios::in);
48 if(!input_file)
49 throw std::runtime_error("Input_File cannot be opened!");
50 string line;
51 /*匹配字符串并进行转换解密**************/
52 while(getline(input_file,line))
53 {
54 //映射入字符串流
55 istringstream stream(line);
56 string word;
57 while(stream>>word)
58 {
59 map<string,string>::const_iterator map_it = trans_map.find(word);
60 if(map_it != trans_map.end())
61 word = map_it->second;
62 cout<<word<<" ";
63 }
64 cout<<endl;
65 }
66 input_file.close();
67 return 0;
68 }
69 catch(std::exception const &ex)
70 {
71 cerr<<ex.what()<<endl;
72 return EXIT_FAILURE; //以错误状态退出
73 }
74 }
75
76