I have an assignment to make a program that converts Infix to Prefix in C++. I have written a code to do so but the problem is I am only getting the operands and not the operators in the final result. I have checked my code many time, dry run it, but I cant find the problem. Here is the code:
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int Prec(char c)
{
if(c == '^')
{
return 3;
}
else if(c == '*' || c == '/')
{
return 2;
}
else if(c == '+' || c == '-')
{
return 1;
}
else
{
return -1;
}
} // prec
string InfixToPrefix(string s)
{
reverse(s.begin(), s.end());
stack<char> st;
string res;
for(int i=0; i<s.length(); i++)
{
if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))
{
res += s[i];
}
else if(s[i] == ')')
{
st.push(s[i]);
}
else if(s[i] == '(')
{
while(!st.empty() && st.top() != ')')
{
res += st.top();
st.pop();
}
if(!st.empty())
{
st.pop();
}
else
{
while(!st.empty() && Prec(st.top()) >= Prec(s[i]))
{
res += st.top();
st.pop();
}
st.push(s[i]);
}
}
} // for loop
while(!st.empty())
{
res+=st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
} // InfixToPrefix()
int main()
{
cout<<InfixToPrefix("(a-b/c)*(a/k-l)")<<endl;
}
Can someone please help?
The correct output should be "*-a/bc-/akl" but I am only getting "abcakl". Please help. Thank you.
You need to put the operator logic in the mainloop.
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int Prec(char c)
{
if(c == '^')
{
return 3;
}
else if(c == '*' || c == '/')
{
return 2;
}
else if(c == '+' || c == '-')
{
return 1;
}
else
{
return -1;
}
} // prec
string InfixToPrefix(string s)
{
reverse(s.begin(), s.end());
stack<char> st;
string res;
for(int i=0; i<s.length(); i++)
{
if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))
{
res += s[i];
}
else if(s[i] == ')')
{
st.push(s[i]);
}
else if(s[i] == '(')
{
while(!st.empty() && st.top() != ')')
{
res += st.top();
st.pop();
}
if(!st.empty())
{
st.pop();
}
else
{
while(!st.empty() && Prec(st.top()) >= Prec(s[i]))
{
res += st.top();
st.pop();
}
st.push(s[i]);
}
}
else { // added operator logic to the main portion of the parse loop
if (!st.empty() && Prec(st.top()) >= Prec(s[i])){
res += st.top();
st.pop();
}
st.push(s[i]);
}
} // for loop
while(!st.empty())
{
res+=st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
} // InfixToPrefix()
int main()
{
cout<<InfixToPrefix("(a-b/c)*(a/k-l)")<<endl;
}