CEBL  2.1
StringTable.cpp
Go to the documentation of this file.
1 #include <map>
2 #include <string>
3 #include <fstream>
4 #include <istream>
5 #include <sstream>
6 #include <iostream>
7 #include <sstream>
8 #include <algorithm>
9 #include <boost/regex.hpp>
10 using namespace std;
11 using namespace boost;
12 
13 #include "StringTable.hpp"
14 #include "../Exceptions.hpp"
15 #include "../CompiledStrings.hpp"
16 
17 
19 
20 
21 void StringTable::loadFromFile(string filename)
22 {
23  ifstream ifs(filename.c_str());
24  if(!ifs.is_open())
25  {
26  throw FileException("String table failed to open \"" + filename + "\".");
27  }
28  this->load(ifs);
29 }
30 
31 
32 void StringTable::loadFromString(string string_table)
33 {
34  string_table = regex_replace(string_table,
35  regex(str_table_linebreak_str),"\n");
36  stringstream is;
37  is << string_table;
38  this->load(is);
39 }
40 
41 
42 void StringTable::load(istream &is)
43 {
44  string line;
45  string buffer;
46 
47  //now parse the file
48  regex string_regexp(string(
49  "^[[:space:]]*(\\w+)[[:space:]]*=")
50  +"[[:space:]]*\"(.+)\"[[:space:]]*");
51 
52  //loop through file
53  while(!is.eof())
54  {
55  // get the next line
56  getline(is, buffer);
57  line = buffer;
58 
59  bool valid = regex_search(line,string_regexp);
60 
61  //check if search failed
62  if(!valid)
63  {
64  // cerr << "StringTable: Bad line: " << line << endl;
65  }
66  else
67  {
68  cmatch what;
69  regex_match(line.c_str(), what, string_regexp);
70  strings[what[1]] = decodeString(what[2]);
71  }
72  }
73 }
74 
75 const char * StringTable::getString(string string_name)
76 {
77  if(strings.count(string_name))
78  {
79  return strings[string_name].c_str();
80  }
81  else
82  {
83  throw StringTableException("Cannot find string of name " + string_name);
84  }
85 }
86 
87 
88 string StringTable::decodeString(string str)
89 {
90  //cout << "string = " << str << "\n";
91  string ret;
92  ret = regex_replace(str,
93  regex("\\\\[n]"),"\n");
94  ret = regex_replace(ret,
95  regex("\\\\[t]"),"\t");
96  ret = regex_replace(ret,
97  regex("\\\\[\"]"),"\\\"");
98  //cout << "string = " << ret << "\n";
99  return ret;
100 }