Infix to Postfix - Debugging Code
Oct 18, 2016 at 2:42am UTC
I've created a basic infix to postfix converter using C++. I have a couple errors that I'm not able to figure out.
1. My do-while loop only displays the sstream output after the first iteration of the loop.
2. My program crashes whenever an arithmetic expression with parenthesis is inserted into the console. For example, (A+B) will crash the program but A+B will not. However, (A) will not crash the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
int precedence(char x);
int main()
{
string infix;
stringstream postfix;
char response; // variable to take Y or N input from user
do
{
postfix.clear();
postfix.str(string());
cout << "Enter an expression in infix notation: " << endl;
getline(cin, infix);
stack<char > operators;
for (unsigned i = 0; i < infix.length(); i++) {
if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/' )
{
while (!operators.empty() && precedence(operators.top()) <= precedence(infix[i]))
{
postfix << operators.top();
operators.pop();
}
operators.push(infix[i]);
}
else if (infix[i] == '(' )
{
operators.push(infix[i]);
}
else if (infix[i] == ')' )
{
while (operators.top() != '(' )
{
postfix << operators.top();
operators.pop();
}
operators.pop();
}
else
{
postfix << infix[i];
}
}
while (!operators.empty()) {
postfix << operators.top();
operators.pop();
}
cout << postfix.str() << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
cout << endl << "Would you like to convert another expression? Enter Y or N: " ;
cin >> response;
} while (response != 'N' );
return 0;
}
int precedence(char x) {
int temp = 0;
if (x == '*' || x == '/' )
{
temp = 1;
}
else if (x == '+' || x == '-' )
{
temp = 2;
}
return temp;
}
Last edited on Oct 18, 2016 at 2:49am UTC
Topic archived. No new replies allowed.