I wrote a c++ code to convert infix expression to postfix expression using stacks but whenever I try to return the popped value from the stack,it's not returning the string.The returned string is null instead of the original content of the stack. Do I need to convert it into char first? strong text
input: A+B
output: AB
correct output: AB+
How to return string from member function in c++?
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000
int top=-1;
string stck[MAX];
void push(char data)
{
top++;
*(stck+top)=data;
}
string pop()
{
if(top<0)
{
return "";
}
else
{
top--;
return (*(stck+top));
}
}
bool isstckempty()
{
if(top==-1){
return true;
}
else
return false;
}
int main()
{
string s;
cin>>s;
string ss="";
int len=s.length();
int j=0;
for(int i=0;i<len;i++)
{
if(isalpha(s[i]))
{
ss=ss+s[i];
}
else
{
if(s[i]=='(')
{
push(s[i]);
}
else if(s[i]==')')
{
j=i-1;
while((s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
ss=ss+pop();
}
else if(s[i]=='+'||s[i]=='-')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
else if(s[i]=='*')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
else if(s[i]=='*')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
}
}
while(!isstckempty){
ss=ss+pop();
}
cout<<ss<<endl;
return 0;
}
Your function pop() returns invalid data when top==0, because you decrement top before indexing the stack, and any array access with a negative index will be undefined. As others have said, don't implement your own stack, use std::stack and more obvious api's.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.