fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <regex>
  4. #include <string>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. enum TOKENS {
  10. OPEN_PARENTHESIS,
  11. NEGATIVE_NUMBER,
  12. NON_NEGATIVE_NUMBER,
  13. CLOSE_PARENTHESIS,
  14. ADDITION,
  15. SUBTRACTION,
  16. MULTIPLICATION,
  17. DIVISION,
  18. EQUALITY,
  19. SIZE_TOKENS
  20. };
  21.  
  22. int main() {
  23. const auto input = "42/2 + -8\t=\n(2 + 2) * 2 * 2 -3"s;
  24. vector<TOKENS> tokens;
  25. const regex re{ "\\s*(\\(?)\\s*(-?\\s*\\d+)\\s*(\\)?)\\s*(?:(\\+)|(-)|(\\*)|(/)|(=))" };
  26.  
  27. for_each(sregex_iterator(cbegin(input), cend(input), re), sregex_iterator(), [&](const auto& i) {
  28. if(i[1].length() > 0) {
  29. tokens.push_back(OPEN_PARENTHESIS);
  30. }
  31.  
  32. tokens.push_back(i[2].str().front() == '-' ? NEGATIVE_NUMBER : NON_NEGATIVE_NUMBER);
  33.  
  34. if(i[3].length() > 0) {
  35. tokens.push_back(CLOSE_PARENTHESIS);
  36. }
  37.  
  38. auto it = next(cbegin(i), 4);
  39.  
  40. for(int result = ADDITION; it != cend(i); ++result, ++it) {
  41. if (it->length() > 0U) {
  42. tokens.push_back(static_cast<TOKENS>(result));
  43. break;
  44. }
  45. }
  46. });
  47.  
  48. match_results<string::const_reverse_iterator> sm;
  49.  
  50. if(regex_search(crbegin(input), crend(input), sm, regex{ tokens.back() == SUBTRACTION ? "^\\s*\\d+\\s*-\\s*(-?)" : "^\\s*\\d+\\s*(-?)" })) {
  51. tokens.push_back(sm[1].length() == 0 ? NON_NEGATIVE_NUMBER : NEGATIVE_NUMBER);
  52. }
  53.  
  54. for (const auto& i : tokens) {
  55. switch (i) {
  56. case NEGATIVE_NUMBER:
  57. cout << "NEGATIVE_NUMBER\n";
  58. break;
  59. case NON_NEGATIVE_NUMBER:
  60. cout << "NON_NEGATIVE_NUMBER\n";
  61. break;
  62. case ADDITION:
  63. cout << "ADDITION\n";
  64. break;
  65. case SUBTRACTION:
  66. cout << "SUBTRACTION\n";
  67. break;
  68. case MULTIPLICATION:
  69. cout << "MULTIPLICATION\n";
  70. break;
  71. case DIVISION:
  72. cout << "DIVISION\n";
  73. break;
  74. case EQUALITY:
  75. cout << "EQUALITY\n";
  76. break;
  77. case OPEN_PARENTHESIS:
  78. cout << "OPEN_PARENTHESIS\n";
  79. break;
  80. case CLOSE_PARENTHESIS:
  81. cout << "CLOSE_PARENTHESIS\n";
  82. }
  83. }
  84. }
Success #stdin #stdout 0s 3564KB
stdin
Standard input is empty
stdout
NON_NEGATIVE_NUMBER
DIVISION
NON_NEGATIVE_NUMBER
ADDITION
NEGATIVE_NUMBER
EQUALITY
OPEN_PARENTHESIS
NON_NEGATIVE_NUMBER
ADDITION
NON_NEGATIVE_NUMBER
CLOSE_PARENTHESIS
MULTIPLICATION
NON_NEGATIVE_NUMBER
MULTIPLICATION
NON_NEGATIVE_NUMBER
SUBTRACTION
NON_NEGATIVE_NUMBER