Conversion of Infix expression to Postfix - c++

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=='\')

Related

When i run this program it does not print the required output given by the called function for checking for balanced parenthesis?

i am currently working on a stack problem which checks for the balanced perenthesis in the input given to it. Maybe i am not able to get the output to be returned to the main function .
here is the code that i wrote to solve the problem:
i am open to any recomendations to improve the code or any suggestions to fairly solve these type of questions .
#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool checkbalancedperanthesis(string exp){
int n;
n = exp.length();
cout<<n;
stack <char> S;
for (int i = 0; i < n-1; i++)
{
if (exp[i] == '[' || exp[i] == '(' || exp[i] == '{')
{
S.push(exp[i]);
}
else if (exp[i] == ']' || exp[i] == ')' || exp[i] == '}')
{
if (S.empty() || S.top() != exp[i])
{
return false;
}
else
{
S.pop();
}
}
}
return (S.empty());
}
int main(){
string exp;
cout<<"Enter the expression you want to test for balanced experessions: ";
cin>>exp;
checkbalancedperanthesis(exp);
cout<<endl;
cout<<exp;
}
S.top() != exp[i] This condition won't work. It will never be true - you are comparing, for example, if ( is equal to ) which will never be true, and it will always return false. You should properly check if the brackets match.
Also, your loop runs till n-2 which leads to not processing last bracket in the expression. It should be changed to n-1, by changing the condition to i < n.
Also, you don't seem to be doing any checking of the return value. You should check it appropriately in your code. For now, I just print the return value.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool checkbalancedperanthesis(string exp) {
int n = exp.length();
//cout << n;
stack <char> S;
// CHANGE HERE
for (int i = 0; i < n; i++)
{
if (exp[i] == '[' || exp[i] == '(' || exp[i] == '{')
{
S.push(exp[i]);
}
else if (exp[i] == ']' || exp[i] == ')' || exp[i] == '}')
{
// CHANGE HERE
char top_val = S.top();
S.pop();
if ((top_val == '(' && exp[i] == ')')
|| (top_val == '[' && exp[i] == ']')
|| (top_val == '{' && exp[i] == '}'))
{
// do nothing
}
else
{
return false;
}
}
}
return S.empty();
}
int main() {
string exp;
cout << "Enter the expression you want to test for balanced experessions:\n";
//cin>>exp;
exp = "[[(){}]]";
cout << exp << " " << checkbalancedperanthesis(exp) << endl;
exp = "[[({}]]";
cout << exp << " " << checkbalancedperanthesis(exp) << endl;
}

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())

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

Why this if(s[j]==s[i] && i>0) condition is not work for this [{()}] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Question link
In this question firstly user will give the number of test cases, for each of the test cases users enter a string like [{()}]. This code if s[i] value equal to any left bracket like '(', '[', '{' then i added it's right bracket into ans string otherwise we have to compare last added character in ans with current s[i] character.
#include <bits/stdc++.h>
using namespace std;
string isBalanced(string s) {
string ans;
int j=-1;
for(int i=0; i<s.length(); i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
if(s[i]=='(')
ans.push_back((char)(s[i]+1));
else ans.push_back((char)(s[i]+2));
j++;
}
else if(s[j]==s[i] && i>0){
ans.pop_back();
j--;
}
}
if(ans.empty()) return "YES";
else return "NO";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
string s;
getline(cin, s);
string result = isBalanced(s);
fout << result << "\n";
}
fout.close();
return 0;
}
Edit. In your code, I found three issues:
You compare s[i] with s[j], while you should made the comparaison with ans[j]
Before using index j, you should first check it is positive.
As soon as the comparaison fails, you should return "NO".
This is your code, corrected:
string isBalanced_OP(string s) {
string ans;
int j = -1;
for (int i = 0; i < s.length(); i++) {
if (s[i]=='(' || s[i]=='[' || s[i]=='{') {
if (s[i]=='(') ans.push_back ((char)(s[i]+1));
else ans.push_back ((char)(s[i]+2));
j++;
}
else if (j < 0) {
return "NO";
} else if (ans[j]==s[i]){
ans.pop_back();
j--;
} else {
return "NO";
}
}
if(ans.empty()) return "YES";
else return "NO";
}
Another important point is that your algorithm seems too complex for this problem.
If you don't have other characters than brackets, you only need to compare current first and current last characters, and no need for string ans. You can return "NO" as soon as you get a mismatch.
string isBalanced(string s) {
int n = s.size();
if (n%2) return "NO";
int i = 0;
int j = n-1;
while (i < j) {
bool check;
check = (s[i] == '(' && s[j] == ')');
check = check || (s[i] == '[' && s[j] == ']');
check = check || (s[i] == '{' && s[j] == '}');
if (!check) return "NO";
++i;
--j;
}
return "YES";
}
Edit: it appears after my first post that a sequence like ()[]{} is well balanced, which is not so clear from the question on the online site, and not mentioned originally in the question here. Therefore, I now provide this second program, based on a stack. The idea is to stack opening brackets, and to check each close bracket with the last character entered in the stack. It appears finally that this code is rather similar to yours, after correction of your code.
string isBalanced2(string s) {
int n = s.size();
if (n%2) return "NO";
std::stack<char> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push (s[i]);
continue;
}
if (st.empty()) return "NO";
char mem = st.top();
st.pop();
bool check;
check = (mem == '(' && s[i] == ')');
check = check || (mem == '[' && s[i] == ']');
check = check || (mem == '{' && s[i] == '}');
if (!check) return "NO";
}
if (st.empty()) return "YES";
else return "NO";
}

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?