ConfReader.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ifndef CONF_READER_H
  2. #define CONF_READER_H
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <fstream>
  7. #include <map>
  8. #include <algorithm>
  9. using namespace std;
  10. struct ConfReader {
  11. static bool isSpace(unsigned char c) {
  12. return (c == ' ' || c == '\n' || c == '\r' ||
  13. c == '\t' || c == '\v' || c == '\f');
  14. };
  15. ConfReader() {};
  16. std::map<string, string> params;
  17. void read_config(const char* fname) {
  18. string str;
  19. ifstream In(fname);
  20. vector<string> v;
  21. string prefix = "";
  22. while ( ! In.eof() ) {
  23. getline (In, str);
  24. str.erase(std::remove_if(str.begin(), str.end(), isSpace), str.end());
  25. int cage;
  26. if((cage = str.find('#')) != string::npos)
  27. str.erase(cage);
  28. if(str[0] == '[')
  29. prefix = str.substr(1, str.find(']')-1);
  30. else if(!str.empty() && str[0] != '#')
  31. v.push_back(prefix + "_" + str);
  32. };
  33. for(int i=0; i<v.size(); i++)
  34. params.insert(std::make_pair(v[i].substr(0, v[i].find('=')), v[i].substr(v[i].find('=')+1) ));
  35. for(int i=0; i<v.size(); i++)
  36. cout << i+1 << " string is \"" << v[i] << "\"" << endl;
  37. std::map<string, string>::iterator it = params.begin();
  38. while(it != params.end()) {
  39. cout << "\'" << it->first << "\' -> \'" << it->second << "\'" << endl;
  40. it++;
  41. };
  42. };
  43. void splitStr(string& str, std::vector<string>& parts) {
  44. int d=0, old_d = 0;
  45. while((d = str.find(',', old_d)) != string::npos) {
  46. parts.push_back(str.substr(old_d, d-old_d));
  47. old_d = d+1;
  48. };
  49. parts.push_back(str.substr(old_d));
  50. };
  51. void getInts(string& key, std::vector<int>& res) {
  52. string s = params[key];
  53. std::vector<string> args;
  54. splitStr(s, args);
  55. for(int i=0; i<args.size(); i++)
  56. res.push_back(std::stoi(args[i]));
  57. };
  58. void getString(string& key, string& res) {
  59. res = params[key];
  60. };
  61. void getDoubles(string& key, std::vector<double>& res) {
  62. string s = params[key];
  63. std::vector<string> args;
  64. splitStr(s, args);
  65. for(int i=0; i<args.size(); i++)
  66. res.push_back(std::stod(args[i]));
  67. };
  68. };
  69. #endif