Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <forward_list>
- using namespace std;
- struct token
- {
- int prec_level;
- string tokenstr;
- };
- std::forward_list<token*> tokens;
- std::forward_list<token*>::iterator it;
- int tokenscount = 0;
- void tokenize(string);
- void createtoken(string,int);
- int parse(int,int);
- int parse_primary();
- char peek_next_token();
- int domath(char, int, int);
- int conv_char_prec();
- int main()
- {
- cout << "Enter an equation with the operators /,*,+,-" << endl;
- string equation;
- int result;
- while (true)
- {
- getline(cin, equation);
- tokenize(equation);
- it = tokens.begin();
- result = parse(parse_primary(), 0);
- cout << result << endl;
- tokens.clear();
- tokenscount = 0;
- }
- }
- void tokenize(string equation)
- {
- string cattoken;
- for (int i = 0; i < equation.length(); i++)
- {
- if (equation.at(i) == ' ')
- continue;
- else if (isdigit(equation.at(i)))
- {
- cattoken = equation.at(i);
- for (i+= 1; isdigit(equation.at(i)); i++)
- {
- ;
- cattoken.append(1, equation.at(i));
- }
- i--;
- createtoken(cattoken, NULL);
- }
- cattoken = equation.at(i);
- if (equation.at(i) == '+')
- createtoken(cattoken, 1);
- if (equation.at(i) == '-')
- createtoken(cattoken, 1);
- if (equation.at(i) == '*')
- createtoken(cattoken, 2);
- if (equation.at(i) == '/')
- createtoken(cattoken, 2);
- }
- createtoken(";", -1);
- }
- int parse(int lhs,int min_preclevel)
- {
- int rhs;
- int lookahead = conv_char_prec();
- char oper = peek_next_token();
- while (lookahead >= min_preclevel)
- {
- int op = lookahead;
- rhs = parse_primary();
- lookahead = conv_char_prec();
- while (lookahead >= op)
- {
- rhs = parse(rhs, lookahead);
- lookahead = conv_char_prec();
- }
- lhs = domath(oper, lhs, rhs);
- }
- return lhs;
- }
- void createtoken(string tokenchar,int prec_level)
- {
- token * tokenptr = new struct token;
- tokenptr->prec_level = prec_level;
- tokenptr->tokenstr = tokenchar;
- tokens.push_front(tokenptr);
- }
- int parse_primary()
- {
- int lhs;
- advance(it, tokenscount);
- tokenscount = 1;
- lhs = stoi((*it)->tokenstr, nullptr, 10);
- return lhs;
- }
- char peek_next_token()
- {
- advance(it, tokenscount);
- return (*it)->tokenstr.at(0);
- }
- int conv_char_prec()
- {
- char lookahead = peek_next_token();
- int lookaheadprec;
- if (lookahead == '+')
- lookaheadprec = 1;
- if (lookahead == '-')
- lookaheadprec = 1;
- if (lookahead == '*')
- lookaheadprec = 2;
- if (lookahead == '/')
- lookaheadprec = 2;
- if (lookahead == ';')
- lookaheadprec = -1;
- return lookaheadprec;
- }
- int domath(char oper, int lhs, int rhs)
- {
- int result;
- if (oper == '+')
- result = lhs + rhs;
- if (oper == '-')
- result = lhs - rhs;
- if (oper == '*')
- result = lhs * rhs;
- if (oper == '/')
- result = lhs / rhs;
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement