float Calculate(const string &query)
{
std::cout << "Query: " << query << "\n";
unsigned int size = query.length();
char stack[70];
float res;
int m = 0;
for (int i = 0; i < size; i++)
{
if (query[i] >= '0' && query[i] <= '9')
{
stack[m] = query[i] - '0';
m++;
continue;
}
switch (query[i])
{
case '+':
{
res = stack[m - 2] + stack[m - 1];
break;
}
case '-':
{
res = stack[m - 2] - stack[m - 1];
break;
}
case '*':
{
res = stack[m - 2] * stack[m - 1];
break;
}
case '/':
{
res = stack[m - 2] / stack[m - 1];
break;
}
}
stack[m - 2] = res;
m--;
cout << "RES: " << res << "\n";
}
return res;
}
It calculates reverse polish notation.
When I call something like: Calculate("11+") it returns right result: 2.
But, when I pass a variable after getting of RPN string:
string inputStr;
string outputStr;
cout << "Put exercise\n";
getline(std::cin, inputStr);
outputStr = GetRPN(inputStr);
cout << "Output str :" << outputStr << ":\n";
float res = Calculate(outputStr);
std::cout << res << "\n";
So, when I input string: 1+1, function GetRPN returns 11+ and I see that in second cout. But result is 0!
What could it be?
string GetRPN(string input)
{
vector <char> operation;
string outputStr; //output string, keep RPN
int stack_count = 0;
for(int i = 0; i < input.length(); i++)
{
if(input[i] >= '0' && input[i] <= '9')
{
outputStr += input[i];
}
else
{
if(operation.empty())
{
operation.push_back(input[i]);
stack_count++;
}
else if(operation[stack_count - 1] == '+' || operation[stack_count - 1] == '-')
{
operation.push_back(input[i]);
stack_count++;
}
else if ((operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/') && (input[i] == '*' || input[i] == '/'))
{
outputStr += operation[stack_count - 1]; // move mark of operation to output str
operation.pop_back(); // delet last element from vector
operation.push_back(input[i]);// plus new operation mark to vector
stack_count++;
}
else if (operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/')
{
outputStr += input[i];
}
}
}
for(int i = operation.size(); i >= 0; i--)
{
outputStr += operation[i]; // move all operation marks to otput str
}
return outputStr;
}
Your cycle here
does not make any sense. You are obviously attempting to access the vector at invalid index. It is illegal to access the element at
operation[i]wheniis equaloperation.size(). The index is out of range.Any self-respecting implementation would immediately report this problem with an assertion. In any case, as I said in the comment, the problems like that are resolved by debugging the code. Why are you asking other people to debug your code instead of doing it yourself?