1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
#include <iostream> #include <vector> #include <string> #include <cctype> // Token types enum class TokenType { Number, Plus, Minus, Multiply, Divide, End, Invalid }; // Token class class Token { public: Token(TokenType type, std::string value) : type(type), value(value) {} TokenType getType() const { return type; } std::string getValue() const { return value; } private: TokenType type; std::string value; }; // Lexer class class Lexer { public: Lexer(const std::string& input) : input(input), index(0) {} Token nextToken() { while (index < input.size() && std::isspace(input[index])) { ++index; } if (index >= input.size()) { return Token(TokenType::End, ""); } char current = input[index]; if (std::isdigit(current)) { std::string number; while (index < input.size() && std::isdigit(input[index])) { number += input[index++]; } return Token(TokenType::Number, number); } switch (current) { case '+': ++index; return Token(TokenType::Plus, "+"); case '-': ++index; return Token(TokenType::Minus, "-"); case '*': ++index; return Token(TokenType::Multiply, "*"); case '/': ++index; return Token(TokenType::Divide, "/"); default: return Token(TokenType::Invalid, std::string(1, current)); } } private: std::string input; size_t index; }; // Parser class class Parser { public: Parser(Lexer& lexer) : lexer(lexer), currentToken(lexer.nextToken()) {} void parse() { while (currentToken.getType() != TokenType::End) { if (currentToken.getType() == TokenType::Number) { std::cout << "Number: " << currentToken.getValue() << std::endl; } else { std::cout << "Operator: " << currentToken.getValue() << std::endl; } currentToken = lexer.nextToken(); } } private: Lexer& lexer; Token currentToken; }; // Main function int main() { std::string input = "10 + 20 * 30 - 40 / 2"; Lexer lexer(input); Parser parser(lexer); std::cout << "Parsing input: " << input << std::endl; parser.parse(); return 0; } |