fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <map>
  4. #include <string>
  5.  
  6. enum token_t
  7. {
  8. END,
  9. PLUS,
  10. NUMBER,
  11. D,
  12. DR,
  13. R,
  14. A,
  15.  
  16. // ...
  17. };
  18.  
  19. // ...
  20.  
  21. using keyword_to_token_t = std::map < std::string, token_t >;
  22.  
  23. keyword_to_token_t kwtt =
  24. {
  25. {"A", A},
  26. {"D", D},
  27. {"R", R},
  28. {"DR", DR}
  29.  
  30. // ...
  31.  
  32. };
  33.  
  34. // ...
  35.  
  36. std::string s;
  37. int n;
  38.  
  39. // ...
  40.  
  41. token_t get_token( std::istream& is )
  42. {
  43. char c;
  44.  
  45. std::ws( is ); // discard white-space
  46.  
  47. if ( !is.get( c ) ) // read a character
  48. return END; // failed to read or eof
  49.  
  50. // analyze the character
  51. switch ( c )
  52. {
  53. case '+': // simple token
  54. return PLUS;
  55.  
  56. case '0': case '1': // rest of digits
  57. is.putback( c ); // it starts with a digit: it must be a number, so put it back
  58. is >> n; // and let the library to the hard work
  59. return NUMBER;
  60. //...
  61.  
  62. default: // keyword
  63. is.putback( c );
  64. is >> s;
  65. if ( kwtt.find( s ) == kwtt.end() )
  66. throw "keyword not found";
  67. return kwtt[ s ];
  68. }
  69. }
  70.  
  71. int main()
  72. {
  73. try
  74. {
  75. while ( get_token( std::cin ) )
  76. ;
  77. std::cout << "valid tokens";
  78. }
  79. catch ( const char* e )
  80. {
  81. std::cout << e;
  82. }
  83. }
  84.  
Success #stdin #stdout 0s 4512KB
stdin
D DR R + A
stdout
valid tokens