Cod sursa(job #2900925)

Utilizator disinfoion ion disinfo Data 12 mai 2022 15:58:21
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#define MAX 100010

using namespace std;
string NUM("1234567890");

vector<string> parse (string s){
	vector<string> toks;
	string curr_number;

	for(auto c:s){
		if(NUM.find(c) != -1){
			curr_number.push_back(c);
		}
		else{
			if(!curr_number.empty()){
				toks.push_back(curr_number);
				curr_number = "";
			}
			toks.push_back(string(1, c));
		}
	}
	if(!curr_number.empty()){
				toks.push_back(curr_number);
				curr_number = "";
			}

	return toks;
}

int where, len;
vector<string> toks;

int factor();

int term();

int eval(){
	int t = term();
	string op = toks[where];
	if(op == "+"){
		++where;
		return t + term();
	}
	else if(op == "-"){
		++where;
		return t - term();
	}
	else{
		return t;
	}
}

int term(){
	int f = factor();
	string op = toks[where];
	if(op == "*"){
		++where;
		return f * factor();
	}
	else if(op == "/"){
		++where;
		return f / factor();
	}
	else{
		return f;
	}
}

int factor(){
	int a;
	if(toks[where] == "("){
		++where;
		a = eval();
		++where;
	}
	else{
		a = stoi(toks[where]);
		++where;
	}
	return a;
}

int main(){
	ifstream fin;
	ofstream fout;
	fin.open("evaluare.in");
	fout.open("evaluare.out");
	string s;
	getline(fin, s);
	len = s.size();
	toks = parse(s);
	toks.push_back(";");
	fout << eval();

}