piromanas
public cpp v1 · immutable#include <iostream>#include <string>#include <sstream>#include <algorithm>#include <cmath>#include <stdlib.h>#include <list> using namespace std;struct token { token *right, *left ; double value ; char operation ; string ID ; token() : right(NULL), left(NULL), value(0), operation(0) {} ; } ; // the tabe of states const int E = 0 ; const int ID = 1 ; const int V = 2 ; const int O = 3 ; const int floating_point = 4 ; const int EXP = 5 ; const int ERROR = 6 ;//------------------------- void lexer (string::iterator begin, string::iterator end, list<token *> & output) { std::string::iterator i, b, e ; int state = E , count = 0 ; while ( i < end ) { switch (state) { case E : if ( isalpha(*i) && i < end ) { b = i ; state = ID ; } else if ( isdigit(*i) && i < end ) { b = i ; state = V ; } else if ( ((*i == '+') || (*i == '-') || (*i == '*') || (*i == '/') || (*i == '^')) && i < end ) { state = O ; } else if ( ((*i) == ' ') && i < end ) { ++i ; state = E ; } else state = ERROR ; break ; case ID : if ( (isalpha(*i) || isdigit(*i)) && i < end ) { state = ID ; ++i ; } else { token* t = new token ; e = i ; string s(b,e) ; t->ID = s ; output.push_back(t) ; state = E ; } break ; case V : if ( isdigit(*i) && i < end ) { state = V ; ++i ; } else if ( (((*i) == ',') || ((*i) == '.')) && i < end ) { state = floating_point ; ++count ; ++i ; } else if ( ((*i == 'E') || (*i == 'e')) && i < end ) { state = EXP ; ++i ; } else { token* t = new token ; e = i ; string s1 (b,e) ; istringstream stream (s1) ; double d ; stream >> d ; t->value = d ; output.push_back(t) ; count = 0 ; state = E ; } break ; case O : if ( ((*i == '+') || (*i == '-') || (*i == '*') || (*i == '/') || (*i == '^')) && i < end ) { token* t = new token ; t->operation = *i ; output.push_back(t) ; ++i ; state = E ; } break ; case floating_point : if ( isdigit(*i) && count < 2 && i < end ) { state = V ; ++i ; } else state = ERROR ; break ; case EXP : if ( isdigit(*i) && i < end ) { state = V ; ++i ; } else state = ERROR ; break ; case ERROR : default : exit(0) ; } } } int main() { string str ; list<token *> output ; getline(cin,str) ; lexer(str.begin(),str.end(),output) ;}