-
Notifications
You must be signed in to change notification settings - Fork 15
/
Exer11_38_2.cpp
71 lines (71 loc) · 1.66 KB
/
Exer11_38_2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <stdexcept>
using std::cout;
using std::endl;
using std::ifstream;
using std::istringstream;
using std::string;
using std::unordered_map;
using std::runtime_error;
unordered_map<string, string> buildMap(ifstream &map_file)
{
unordered_map<string, string> trans_map;
string key, 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 + " at " + __func__);
}
return trans_map;
}
const string& transform(const string &s, const unordered_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);
string text;
while(getline(input, text))
{
istringstream stream(text);
string word;
bool firstword = true;
while(stream >> word)
{
// process leading space
if(firstword)
firstword = false;
else
cout << " ";
// process word
cout << transform(word, trans_map);
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
if(argc != 3)
return -1;
ifstream map_file(argv[1]), input_file(argv[2]);
try
{
word_transform(map_file, input_file);
}
catch(runtime_error err)
{
cout << "Error: " << err.what() << endl;
}
return 0;
}