Pagini recente » Cod sursa (job #990625) | Cod sursa (job #3193024) | Cod sursa (job #111790) | Cod sursa (job #2552809) | Cod sursa (job #2900955)
#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(){
//cout << "eval call: " << where << endl;
int t = term();
while(toks[where] == "+" || toks[where] == "-"){
if(toks[where++] == "+"){
//cout << "ok" << endl;
t = t + term();
}
else{
t = t - term();
}
}
//cout << "eval call result: " << t << endl;
return t;
}
int term(){
//cout << "term call: " << where << endl;
int f = factor();
int ans;
while(toks[where] == "*" || toks[where] == "/"){
if(toks[where++] == "*")
f = f * factor();
else
f = f / factor();
}
//cout << "term call result: " << f << endl;
return f;
}
int factor(){
int a;
//cout << "factor call: " << where << " toks: " << toks[where] << endl;
if(toks[where] == "("){
++where;
a = eval();
++where;
}
else{
a = stoi(toks[where]);
++where;
}
//cout << "factor call result: " << a << endl;
return a;
}
int main(){
ifstream fin;
ofstream fout;
fin.open("evaluare.in");
fout.open("evaluare.out");
string s;
getline(fin, s);
//cout << s << endl;
toks = parse(s);
toks.push_back(")");
fout << eval();
}