fork(7) download
  1. #include <map>
  2. #include <sstream>
  3. #include <stdexcept>
  4. #include <string>
  5.  
  6. std::map<std::string, std::string> options; // global?
  7.  
  8. void parse(std::istream & cfgfile)
  9. {
  10. for (std::string line; std::getline(cfgfile, line); )
  11. {
  12. std::istringstream iss(line);
  13. std::string id, eq, val;
  14.  
  15. bool error = false;
  16.  
  17. if (!(iss >> id))
  18. {
  19. error = true;
  20. }
  21. else if (id[0] == '#')
  22. {
  23. continue;
  24. }
  25. else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
  26. {
  27. error = true;
  28. }
  29.  
  30. if (error) { throw std::runtime_error("Parse error"); }
  31.  
  32. options[id] = val;
  33. }
  34. }
  35.  
  36. #include <iostream>
  37.  
  38. int main()
  39. {
  40. parse(std::cin);
  41. for (const auto& p : options)
  42. {
  43. std::cout << "Option['" << p.first << "'] = " << p.second << '\n';
  44. }
  45. }
Success #stdin #stdout 0s 3468KB
stdin
a = 10
b = bob
# this is a comment
c = 1,2,3
stdout
Option['a'] = 10
Option['b'] = bob
Option['c'] = 1,2,3