#include "StdAfx.h"
#include "Calc.h"
#include "string"
Calc::Calc()
{
result = "";
operation = "";
ilLiczb = 0;
ilZnakow = 0;
}
void Calc::RPN(string operation)
{
Stos *stack = new Stos;
result = "";
ilLiczb=0;
ilZnakow=0;
for( unsigned int i=0; i < operation.size() ; i++)
{
if ((operation[i] >= '0' && operation[i] <= '9')) {
result += operation[i];
if (!(operation[i+1] >= '0' && operation[i+1] <= '9')) {
result += " ";
ilLiczb++;
}
}
else if (operation[i] == '*' || operation[i] == '/' || operation[i] == '-'|| operation[i] == '+')
{
if(stack->Top()==NULL)
{
stack->Push((int)operation[i]);
ilZnakow++;
}
else
{
char x = operation[i];
char y = stack->Pop();
if((y == '*' || y == '/') || ((y == '+' || y == '-') && x != '*' && x != '/'))
{
result += y;
result += " ";
while(stack->GetNumbers()>0)
{
result += stack->Pop();
result += " ";
}
stack->Push(x);
}
else
{
stack->Push(y);
stack->Push(x);
}
ilZnakow++;
}
}
else
{
if(operation[i] != ' ')
{
ex = "Wystapily niepoprane znaki w wyrazeniu (np. litery)!";
throw ex;
}
}
}
while(stack->GetNumbers()>0)
{
result += stack->Pop();
result += " ";
}
if(ilLiczb != ilZnakow + 1)
{
ex = "Niepoprawne wyrazenie (ilosc znakow musi byc o jeden mniejsza od ilosci liczb) ";
throw ex;
}
Result(result);
}
void Calc::Result(string operation)
{
Stos *stack2 = new Stos;
stack2->Pop();
int op;
int op2;
//std::string wymik;
string wymik;
string res;
for(unsigned int i=0; i < operation.size(); i++)
{
res = "";
int k = 200;
if ((operation[i] >= '0' && operation[i] <= '9')) {
for(int j=i; j < k; j++)
{
if(operation[j] != ' ')
{
res += operation[j];
i=j;
}
else
{
k=j;
}
}
stack2->Push(atoi(res.c_str()));
}
else if(operation[i] == '*')
{
op2 = stack2->Pop() * stack2->Pop();
stack2->Push(op2);
}
else if(operation[i] == '/')
{
op2 = stack2->Pop();
if (op2 != 0)
{
op = stack2->Pop() / op2;
stack2->Push(op);
}
else {
ex = "Blad dzielenia przez zero!";
throw ex;
}
}
else if(operation[i] == '+')
{
op2 = stack2->Pop() + stack2->Pop();
stack2->Push(op2);
}
else if(operation[i] == '-')
{
op2 = stack2->Pop();
op = stack2->Pop() - op2;
stack2->Push(op);
}
else if(operation[i] == ' ')
{
}
else
{
ex = "Blad - nieznany znak!";
throw ex;
}
}
wymik = stack2->Pop();
}
Calc::~Calc(void)
{;
}