fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4.  
  5. struct PlayerClass
  6. {
  7. std::string const name;
  8.  
  9. unsigned Str, Dex, Int;
  10.  
  11. PlayerClass( std::string const& name ):
  12. name{name} {}
  13.  
  14. PlayerClass& operator=(PlayerClass const&) = delete; // Keine Zuweisung (geht sowieso nicht)
  15. };
  16.  
  17. #include <vector>
  18. #include <algorithm>
  19. #include <functional>
  20. #include <stdexcept>
  21.  
  22. std::istream& operator>>( std::istream& is, PlayerClass& plcl )
  23. {
  24. static std::vector<std::ctype_base::mask> equals_mask;
  25. if( equals_mask.empty() )
  26. {
  27. equals_mask.assign( std::ctype<char>::classic_table(), std::ctype<char>::classic_table() + std::ctype<char>::table_size);
  28. equals_mask['='] |= std::ctype_base::space;
  29. }
  30.  
  31. auto old_loc = is.imbue( std::locale{is.getloc(), new std::ctype<char>{equals_mask.data()} } );
  32.  
  33. std::string attr_str;
  34. unsigned attr_val;
  35. while( is >> attr_str >> attr_val )
  36. {
  37. std::transform( std::begin(attr_str), std::end(attr_str), std::begin(attr_str), std::bind( std::tolower<char>, std::placeholders::_1, old_loc ) ); /// Den String komplett ohne Großbuchstaben machen
  38.  
  39. if( attr_str == "str" ) plcl.Str = attr_val;
  40. else if( attr_str == "dex" ) plcl.Dex = attr_val;
  41. else if( attr_str == "int" ) plcl.Int = attr_val;
  42. else
  43. throw std::logic_error("Invalid attribute while parsing PlayerClass!");
  44. }
  45.  
  46. is.imbue( old_loc );
  47.  
  48. return is;
  49. }
  50.  
  51. #include <sstream>
  52.  
  53. int main()
  54. {
  55. std::istringstream stream("Str=12 \n Dex=17 \n Int=4");
  56. PlayerClass test("Schurke");
  57. stream >> test;
  58.  
  59. std::cout << "Str: " << test.Str << " Dex: " << test.Dex << " Int: " << test.Int;
  60. }
  61.  
  62.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Str: 12 Dex: 17 Int: 4