Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- class parser {
- public:
- int parse(const char *expr)
- {
- m_buffer = expr;
- m_pos = 0;
- int res;
- parse_expression(res);
- return res;
- }
- private:
- std::stack<int> m_stack;
- int m_pos;
- const char *m_buffer;
- bool parse_expression(int &num)
- {
- save();
- if (parse_multiplication(num) || parse_addition(num))
- return commit();
- if (parse_number(num))
- return commit();
- return restore();
- }
- bool parse_addition(int &num)
- {
- save();
- int a;
- if (!(parse_subexpression(a) || parse_number(a)))
- return restore();
- if (!parse_char('+'))
- return restore();
- int b;
- if (!(parse_subexpression(b) || parse_number(b)))
- return restore();
- num = a + b;
- return commit();
- }
- bool parse_char(char ch)
- {
- save();
- if (m_buffer[m_pos] == ch) {
- m_pos++;
- return commit();
- }
- return restore();
- }
- bool parse_multiplication(int &num)
- {
- save();
- int a;
- if (!(parse_addition(a) || parse_number(a) || parse_subexpression(a)))
- return restore();
- if (!parse_char('*'))
- return restore();
- int b;
- if (!(parse_addition(b) || parse_number(b) || parse_subexpression(b)))
- return restore();
- num = a * b;
- return commit();
- }
- bool parse_subexpression(int &num)
- {
- save();
- if (parse_char('(')) {
- if (!parse_expression(num))
- return restore();
- if (!parse_char(')'))
- return restore();
- return commit();
- }
- return restore();
- }
- bool parse_number(int &num)
- {
- save();
- num = 0;
- if (is_numeric()) {
- do {
- num *= 10;
- num += current_seek() - '0';
- } while (is_numeric());
- return commit();
- }
- return restore();
- }
- bool is_numeric()
- {
- return current() >= '0' && current() <= '9';
- }
- char current()
- {
- return m_buffer[m_pos];
- }
- char current_seek()
- {
- char ch = current();
- m_pos++;
- return ch;
- }
- void save()
- {
- m_stack.push(m_pos);
- }
- bool restore()
- {
- m_pos = m_stack.top();
- m_stack.pop();
- return false;
- }
- bool commit()
- {
- m_stack.pop();
- return true;
- }
- };
- int main()
- {
- parser p;
- int num = p.parse("2+5*3+4");
- std::cout << "res: " << num << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement