fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <map>
  5. #include <algorithm>
  6. #include <vector>
  7.  
  8. size_t find(const std::string& line, std::vector<std::string> vect, int pos=0) {
  9. int eol1;
  10. eol1 = 0;
  11. for (std::vector<std::string>::iterator iter = vect.begin(); iter != vect.end(); ++iter) {
  12. //std::cout << *iter << std::endl;
  13. int eol2 = line.find(*iter, pos);
  14. if (eol1 == 0 && eol2 > 0)
  15. eol1 = eol2;
  16. else if (eol2 > 0 && eol2 < eol1)
  17. eol1 = eol2;
  18. }
  19. return eol1;
  20. }
  21.  
  22. std::map<std::string, std::string> mappify(std::string const& s, char delim='=') {
  23. std::map<std::string, std::string> m;
  24.  
  25. std::string::size_type key_pos = 0, i, j;
  26. std::string::size_type key_end;
  27. std::string::size_type val_pos;
  28. std::string::size_type lim_pos;
  29. std::string::size_type val_end;
  30.  
  31. while ((key_end = s.find(delim, key_pos)) != std::string::npos) {
  32. if ((val_pos = s.find_first_not_of(delim, key_end + 1)) == std::string::npos)break;
  33. while (key_end - 1 > 0 && (s[key_end - 1] <= 32 || s[key_end - 1] == ';'))
  34. key_end--;
  35. while (val_pos < s.size() && (s[val_pos] <= 32 || s[val_pos] == ';'))
  36. val_pos++;
  37. val_end = s.find('\n', val_pos);
  38. i = s.find('\"', val_pos);
  39. if (i != std::string::npos)
  40. j = s.find('\"', i + 1);
  41. else
  42. j = 0;
  43. lim_pos = find(s.substr(0, i), { " ",";","\t" }, val_pos + 1);
  44. //std::cout << "s.substr(j):" << s.substr(j)<<std::endl;
  45. if (lim_pos == 0 && j != std::string::npos)lim_pos = find(s.substr(j), { " ",";","\t" }) + j;
  46. if (lim_pos < val_pos)lim_pos = val_pos + 1;
  47. if (j > 0)val_end = j + 1;
  48. if (val_end > lim_pos)val_end = lim_pos;
  49. m.emplace(s.substr(key_pos, key_end - key_pos), s.substr(val_pos, val_end - val_pos));
  50. key_pos = val_end;
  51. while ((key_pos < s.size() && s[key_pos] <= 32 || s[key_pos] == ';'))
  52. ++key_pos;
  53. if (val_end == 0)break;
  54. }
  55. return m;
  56. }
  57. int main() {
  58. std::string s ="\
  59. File=\"c:\\dir\\ocean\\\nCCS_test.txt\"\n\
  60. iEcho=10000; iHrShift=0 rho_Co2 = 1.15d0;\n\
  61. Liner=01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  62. auto m = mappify(s);
  63. for (auto const& p : m)
  64. std::cout << '{' << p.first << " :=> " << p.second << '}' << '\n';
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0s 5644KB
stdin
Standard input is empty
stdout
{File :=> "c:\dir\ocean\
CCS_test.txt"}
{Liner :=> 0}
{iEcho :=> 10000}
{iHrShift :=> 0}
{rho_Co2 :=> 1.15d0}