Post fix calculator, returns wrong value - c++

I'm Writing a program to implement postfix calculator, its giving me completely wrong answers.
Really appreciate the help
class stacks {
public:
typedef int List;
static const int size = 100;
stacks() {
use = 0;
}
void push(List entry) {
data[use] = entry;
++use;
}
List pop() {
if(!empty()) {
--use;
return data[use];
}
}
bool empty() const {
return use == 0;
}
int Size() const {
return use;
}
private:
List data[size];
int use;
};
int main() {
stacks s;
string input;
int final;
ifstream infile("foo.txt",ios::in);
while (getline(infile, input))
cout << "Expression: ";
for (int i = 0; i<input.length(); i++) {
cout << input[i];
auto oper1 = s.pop();
auto oper2 = s.pop();
if(input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' || nput[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
s.push(input[i] - '0');
if(input[i] == '+')
s.push(oper1 + oper2);
if(input[i] == '-')
s.push(oper1 - oper2);
if(input[i] == '*')
s.push(oper1 * oper2);
if(input[i] == '/')
s.push(oper1 / oper2);
}
final = s.pop();
cout << endl << "Value = " << final << "." << endl << endl;
}
What do you recommend?
Thanks

You need to wait to pop() until you know you have an operator. You're popping stuff off the stack when you shouldn't be.

Related

Made an infix to postfix converter and calculator using an array based stack in c++. The calculations don't work. Only returns the top of the stack

My problem is that my evaluatePostfix() function is not calculating operands. It only returns the top of the stack in the converted postfix expression.
So for example, my output is:
Enter a infix expression: 1+4
your postfix expression is:
14+
your result is:
4
Why am I not getting 5?
Here's my main():
int main()
{
string infixExp = "";
cout << "Enter a infix expression: ";
cin >> infixExp;
cout << "your postfix expression is: " << endl;
infixToPostfix(infixExp);
cout << endl;
cout << "your result is: " << endl;
cout << evaluatePostfix(infixExp) << endl;
}
Here's evaluatePostfix():
int evaluatePostfix(string expression)
{
ArrayStack<int> S;
for (int i = 0; i < expression.length(); i++)
{
if (expression[i] == ' ' || expression[i] == ',') continue;
else if(IsOperator(expression[i]))
{
int operand2 = S.peek();
S.pop();
int operand1 = S.peek();
S.pop();
int result = PerformOperation(expression[i], operand1, operand2);
S.push(result);
}
else if(IsNumericDigit(expression[i]))
{
int operand = 0;
while (i < expression.length() && IsNumericDigit(expression[i]))
{
operand = operand * 10 + expression[i] - '0';
i++;
}
i--;
S.push(operand);
}
}
return S.peek();
}
Here's PerformOperation(), IsOperator(), IsNumericDigit(). These are all in evaluatePostfix.
bool IsNumericDigit(char C)
{
if (C >= '0' && C <= '9')
{
return true;
}
else
{
return false;
}
}
bool IsOperator(char C)
{
if (C == '+' || C == '-' || C == '*' || C == '/')
{
return true;
}
else
{
return false;
}
}
int PerformOperation(char operation, int operand1, int operand2)
{
if (operation == '+')
{
return operand1 + operand2;
}
else if (operation == '-')
{
return operand1 - operand2;
}
else if (operation == '*')
{
return operand1 * operand2;
}
else if (operation == '/')
{
return operand1 / operand2;
}
else
{
cout << "error" << endl;
}
return -1;
}
Lastly, here is infixToPostfix():
void infixToPostfix(string s)
{
ArrayStack<char> stackPtr;
string postfixExp;
for (int i = 0; i < s.length(); i++)
{
char ch = s[i];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
{
postfixExp += ch;
}
else if (ch == '(')
{
stackPtr.push('(');
}
else if (ch == ')')
{
while(stackPtr.peek() != '(')
{
postfixExp += stackPtr.peek();
stackPtr.pop();
}
stackPtr.pop();
}
else
{
while (!stackPtr.isEmpty() && prec(s[i]) <= prec(stackPtr.peek()))
{
postfixExp += stackPtr.peek();
stackPtr.pop();
}
stackPtr.push(ch);
}
}
while (!stackPtr.isEmpty())
{
postfixExp += stackPtr.peek();
stackPtr.pop();
}
cout << postfixExp << endl;
}

How come the open and close brackets not showing in the output?

In C++, I am trying to convert these infix expressions (, ), +, -, *, and / to postfix using stacks, but the output does not print out all of the inputs. Parenthesis is not showing in the output after the program runs. There are no errors too.
This image shows the output after it compiles:
The code:
#include <iostream>
#include <stack>
#include <strings.h>
using namespace std;
int operatorPrecedence(char operators);
void infixtoPostfix(string exp);
int main()
{
string exp;
cout << "Enter Infix Expression: "; cin >> exp;
infixtoPostfix(exp);
return 0;
}
int operatorPrecedence(char operators){
//Checking precedence of operators
if (operators == '/') return 2;
else if (operators == '*') return 2;
else if (operators == '+') return 1;
else if (operators == '-') return 1;
else return -1;
}
void infixtoPostfix(string exp){
stack<char> s;
s.push('N');//Element in stack to indicate end of stack
int len = exp.length();
string ns;//Final string for result
for(int i = 0; i < len; i++){
//Storing operand into display string
if ((exp[i] >= 'A' && exp[i] <= 'Z') || (exp[i] >= 'a' && exp[i] <='z') || (exp[i] >= '0' && exp[i] <= '9'))
ns += exp[i];
//Checking for braces/Parentheses
else if (exp[i] == '(')
s.push(exp[i]);
else if (exp[i] == ')'){
while (s.top() != 'N' && s.top() != '('){
char c = s.top();
s.pop();
ns += c;
}
//Popping parentheses if empty
if (s.top() == '('){
char c = s.top();
s.pop();
}
}
else{
//Checking whether scanned operator is less than operator stored in the stack
while (s.top() != 'N' && operatorPrecedence(exp[i]) <= operatorPrecedence(s.top())){
char c = s.top();
s.pop();
ns += c;
}
s.push(exp[i]);
}
}
//Popping out everything else stored in the stack
while (s.top() != 'N'){
char c = s.top();
s.pop();
ns += c;
}
cout << "Postfix Expression: " << ns << endl;
}

Infix to postfix (cpp)

I put the following code together to transform infix to postfix. However it only works when the infix is parenthesised, and I have no clue why. I tried a lot of the basic stuff like directly/indirectly assigning the values.
Here's the code
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
class Expressions
{
public:
std::stack <char> inFix;
std::stack <char> postFix;
std::vector <char> postFixString;
void ptInFix(); // prints the infix and deletes the stack, for testing only, need to tweak later
void ptPostFix();
void inFixtoPostFix();
};
void Expressions::inFixtoPostFix()
{
int size = inFix.size();
for(int i=0;i<size;i++)
{
if((inFix.top() >= 'a' && inFix.top() <= 'z')||(inFix.top() >= 'A' && inFix.top() <= 'Z'))
{
postFixString.push_back(inFix.top());
inFix.pop();
}
else if(inFix.top() == '(')
{
postFix.push(inFix.top());
inFix.pop();
}
else if(inFix.top() == ')')
{
while(postFix.top() != '(')
{
postFixString.push_back(postFix.top());
postFix.pop();
}
if(postFix.top()=='(')
{
postFix.pop();
}
inFix.pop();
}
else if(inFix.top() == '^' || inFix.top() == '*' || inFix.top() == '/' || inFix.top() == '+' || inFix.top() == '-')
{
if(postFix.empty())
{
postFix.push(inFix.top());
inFix.pop();
}
else if(postFix.empty()!=1)
{
while((prec(postFix.top())>=prec(inFix.top())))
{
char c = postFix.top();
postFix.pop();
postFixString.push_back(c);
}
postFix.push(inFix.top());
inFix.pop();
}
}
}
int s = postFix.size();
for(int i=0;i<s;i++)
{
postFixString.push_back(postFix.top());
postFix.pop();
}
}
And this works
Expressions test;
char infix[] = ("(A+B)*(C+D)");
for(int i=(sizeof(infix)-1);i>=0;i--)
{
test.inFix.push(infix[i]);
}
test.inFixtoPostFix();
std::cout<<"\n";
for(int i=0; i<test.postFixString.size(); i++)
{
printf("%c ",test.postFixString[i]);
}
std::cout<<"\n";
But this doesn't, does not output anything at all
Expressions test2;
char infix2[] = ("A+B*C+D");
for(int i=(sizeof(infix2)-1);i>=0;i--)
{
test2.inFix.push(infix2[i]);
}
test2.inFixtoPostFix();
std::cout<<"\n";
int s = test2.postFixString.size();
for(int i=0; i<s; i++)
{
std::cout<<(test2.postFixString[i]) ;
}
std::cout<<"\n";
Since every time I ran the second test case the command window studderes so I suspect there's some kind of memory issue but have not idea where. I had a lot of outputs in the actual function to debug but didn't help so I deleted those for clearity.

Why I am not getting desired output for my c++ problem

I am solving a question which states: to change every '?' with 'a' in a string if doesn't contain if won't form consecutive 'a' else substitute with 'b', eg. a?b will be abb and not aab because here 2 a's are consecutive.
My problem is for i = 3 my string should be over- written with 'b ' according to my code it is entering into the desired block but the string does n't gets written with b, but in all the other case where it should be witten with 'a' it get's written .Help me out with these.
You can refer the problem statement from here to for better understanding my problem :https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/exploring-ruins/
#include <iostream>
using namespace std;
int main() {
string str;
cin >> str;
int n = str.size();
for(int i = 0; i < str.size(); i++) {
if(str[i] == '?') {
if(i == 0) {
if(str[i + 1] == 'a')
str[i] = 'b';
else
str[i] = 'a';
cout << "I am in if" << endl;
} else if(i == n - 1) {
if(str[i - 1] == 'a')
str[i] == 'b';
else
str[i] == 'a';
cout << "I am in if of else if " << endl;
} else {
if(str[i + 1] == 'a' || str[i - 1] == 'a') {
str[i] == 'b';
cout << "I am in if of else " << endl;
} else {
str[i] = 'a';
cout << "I am in else of else " << endl;
}
}
cout << str[i] << endl;
} else
continue;
}
cout << str << endl;
return 0;
}
Given string : ?ba??b
desired output : ababab
my output : aba?ab
It will be a lot easier for you if you would use functions to solve this problem.
bool check_neighbors_for_a(const string &str, size_t place) {
bool result = false;
if (place > 0) { // If there is a char before the current char
result = str[place - 1] == 'a'; // If the previous char is 'a' result become true
}
if (place < str.size() - 1) { // If there is a char after the current char
result = result || str[place + 1] == 'a'; // If the result has become true before this line, result will stay true. Else, result will be true if the next char is equal to 'a'.
// For example: b?a => result = (false || 'a' == 'a')
// For example: a?b => result = (true || 'b' == 'a')
// For example: a?a => result = (true || 'a' == 'a')
}
return result;
}
void replace_questions_by_a(string &str) {
for (size_t i = 0; i < str.size(); i++) {
if (str[i] == '?') {
if (check_neighbors_for_a(str, i)) { // If one of the neighbors is equal to 'a'
str[i] = 'b'; // Place 'b' instead of '?'
} else {
str[i] = 'a'; // Place 'a' instead of '?'
}
}
}
}

Arithmetic Evaluation using Stacks and Postfix Notation

I'm a C++ newcomer.
For the next project in class, the professor asked us to code a program that calculates a mathematical expression, that we input an infix notation, convert it to postfix and calculates it. I think I have pretty much finished the code, but there are some lines that I'm probably doing wrong and I don't really know what is it. Can you please take a look at it and tell me why am I wrong.
#include <iostream>;
#include <stack>;
#include <string>;
using namespace std;
bool operatorCheck(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/')
{
return true;
}
return false;
}
int priority(char c)
{
if (c == '*' || c == '/')
{
return 2;
}
else if (c == '+' || c == '-')
{
return 1;
}
return 0;
}
string InfixToPostfix(string expression)
{
stack<char> operators;
string postfix;
for (int i = 0;i< expression.length();i++)
{
if (expression[i] == ' ')
{
continue;
}
else if (expression[i] >= '0' && expression[i] <= '9')
{
string temp;
temp += expression[i];
int temp2 = i + 1;
while (true)
{
if (expression[temp2] >= '0' && expression[temp2] <= '9')
{
temp += expression[temp2];
temp2 += 1;
}
else
{
break;
}
}
postfix= postfix + temp + " ";
}
else if (operators.empty())
{
operators.push(expression[i]);
}
else if (operatorCheck(expression[i]))
{
if (priority(operators.top()) < priority(expression[i]))
{
operators.push(expression[i]);
}
else
{
while (!operators.empty() && priority(operators.top()) < priority(expression[i]))
{
postfix += operators.top();
operators.pop();
}
operators.push(expression[i]);
}
}
else if (expression[i] == '(')
{
operators.push(expression[i]);
}
else if (expression[i] == ')')
{
while (!operators.empty() && operators.top() != '(')
{
postfix += operators.top();
operators.pop();
}
operators.pop();
}
}
while (!operators.empty())
{
postfix += operators.top();
operators.pop();
}
return postfix;
}
//Main program
int main()
{
string expression;
stack<int> calc;
cout << "Welcome to my program!" << endl;
cout << "This program will help you to calculate arithmetic expression." << endl;
cout << "Please enter an arithmetic expression (Remember to enter space between numbers and operators):" << endl;
getline(cin, expression);
string postfix = InfixToPostfix(expression);
cout << postfix << endl;
for (int i = 0;i < postfix.length();i++)
{
if (postfix[i] == ' ')
{
continue;
}
else if (postfix[i] >= '0' && postfix[i] <= '9')
{
string temp;
int temp2 = i + 1;
temp += postfix[i];
while (true)
{
if (postfix[temp2] >= '0' && postfix[temp2] <= '9')
{
temp += expression[temp2];
temp2 += 1;
}
else
{
break;
}
}
int n = atoi(temp.c_str());
calc.push(n);
}
else if (postfix[i] == '+')
{
int temp1 = calc.top();
calc.pop();
int temp2 = calc.top();
calc.pop();
int result = temp2 + temp1;
calc.push(result);
}
else if (postfix[i] == '-')
{
int temp1 = calc.top();
calc.pop();
int temp2 = calc.top();
calc.pop();
int result = temp2 - temp1;
calc.push(result);
}
else if (postfix[i] == '*')
{
int temp1 = calc.top();
calc.pop();
int temp2 = calc.top();
calc.pop();
int result = temp2 * temp1;
calc.push(result);
}
else if (postfix[i] == '/')
{
int temp1 = calc.top();
calc.pop();
int temp2 = calc.top();
calc.pop();
int result = temp2 / temp1;
calc.push(result);
}
}
cout << calc.top() << endl;
}
For example, with this expression ( ( 7 + 6 ) * ( 16 - 2 ) ) / 2,
It returns 7 6 +16 6 2 -*2 / ( there is an extra 6) for the postfix. Why is this happened?