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())
Related
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=='\')
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;
}
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;
}
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.
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?