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

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;
}

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;
}

Conversion of Infix expression to Postfix

Below is the program i have written to convert a infix expression to postfix. It does give an output but its not always the right one. For example if we input the expression A+B*C-D/F+G , the expected output is ABC*+DF/G+- but rather the program outputs AB+C*D-F/G+. What is the problem in the program.
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
int prec(char oper){
if(oper == '^')
return 3;
else if(oper == '*' || '/')
return 2;
else if(oper == '+' || '-')
return 1;
else
return -1;
}
string itp(string s){
stack<char> stack;
string output = "";
int num = s.length();
for(int i = 0 ; i < num ; i++){
char ch = s[i];
if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')||(ch>='0' && ch<='9'))
output = output + ch;
else if(ch == '(')
stack.push('(');
else if(ch == ')'){
while(stack.top()!='('){
output = output + stack.top();
stack.pop();
}
stack.pop();
}
else{
while(!stack.empty() && prec(s[i]) <= prec(stack.top())){
output = output + stack.top();
stack.pop();
}
stack.push(ch);
}
}
while (!stack.empty()) {
output = output + stack.top();
stack.pop();
}
return output;
}
int main(){
string question;
cout<<"Enter the infix expression : ";
cin >> question;
cout<<endl<<"Postfix expression : "<<itp(question);
return 0;
}
Here:
else if(oper == '*' || '/')
you are using || wrongly. If you consider operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) you will see that == has higher rank than ||, hence it is parsed as
else if( (oper == '*') || '\')
The first part will evaluate to true or false but as \ is not equal to 0, it will be true always, hence in total the condition is true always.
What you want is
else if( oper=='*' || oper=='\')

My program of infix to postfix gives runtime error

Below is an simple program to convert infix expression to postfix expression. It takes an infix expression in main program and after passing values in function converter, it returns a postfix expression as string.
#include<iostream>
#include<stdio.h>
#include<string>
#include <stack>
using namespace std;
int priority(char o) {
if (o == '(' || o == ')')
return -1;
else if (o == '*' || o == '/')
return 2;
else if (o == '+' || o == '-')
return 1;
else if (o == '^' )
return 3;
}
string converter(stack <char>s, string in) {
string pf;
int i;
for (i = 0; i < in.length(); i++) {
if ((in[i] >= 'a' && in[i] <= 'z') || (in[i] >= 'A' && in[i] <= 'Z') ){
pf+= in[i];
}
else if (in[i] == '(') {
s.push(in[i]);
}
else if (in[i] == ')') {
while (s.top() != '(' && (!s.empty())) {
char temp = s.top();
pf += temp;
s.pop();
}
}
else {
if (s.empty()) {
s.push(in[i]);
}
else {
if (priority(in[i]) > s.top()) {
s.push(in[i]);
}
else if (priority(in[i]) == s.top()&&(in[i]=='^')) {
s.push(in[i]);
}
else {
while (priority(in[i]) <= s.top()&&(!s.empty())) {
char temp = s.top();
pf += temp;
s.pop();
}
s.push(in[i]);
}
}
}
}
while (!s.empty()) {
char temp = s.top();
pf += temp;
s.pop();
}
return pf;
}
int main() {
string infix,postfix;
cout << "input an infix expression"<<endl;
cin >> infix;
stack <char> s;
postfix = converter(s, infix);
cout << "Postfix expression is:" << postfix;
return 0;
}
Every time I try to run the program, it gives runtime error.
It works till taking an infix expression but the function aborts abnormally.
I can't find the bug. I use visual studios. Is it a problem in my visual studios or a logic error, really don't know.
This bit:
while (priority(in[i]) <= s.top()&&(!s.empty()))
Accessing a stack's top when it's empty invokes undefined behavior, and that's exactly what's happening here, as priority(in[i]) <= s.top() will be checked first.
You should move the !s.empty() condition first. If it evaluates to true then the second condition will not be checked. This is called Short-circuit evaluation.
while (!s.empty() && priority(in[i]) <= s.top())

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?

i have an issue with my Code which converts infix to postfix

Any expression that contains ( like (5+6) a runtime error occurs don't know why ... i traced the program a lot but couldn't find the error ... my code :
int main() {
string infix, temp = "";
cin >> infix;
stack<char> S;
for (int i = 0; i < infix.length(); i++){
if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/'){
if (!S.empty() && priority(S.top()) <= priority(infix[i])){
while (!S.empty()){
temp += S.top();
S.pop();
}
}
S.push(infix[i]);
}
else if (infix[i] == '('){
S.push(infix[i]);
}
else if (infix[i] == ')'){
while (!S.empty() && S.top() != '('){
temp += S.top();
S.pop();
}
S.pop();
}
else
temp += infix[i];
}
while (!S.empty()){
temp += S.top();
S.pop();
}
cout << temp << endl;
}
thanks in advance :)