2017-10-17 32 views
-3

我写了一个C++代码使用堆栈转换表达后缀表达,但每当我试图从堆栈返回弹出的价值,它不是返回string.The返回字符串为空而不是堆栈的原始内容。 我需要先将它转换为char吗? 强文本如何从功能在C++中返回字符串

输入:A + B

输出:AB

正确的输出:AB +

如何从成员函数在C返回字符串++?当顶== 0,因为你索引堆栈之前递减顶部

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

bits/stdC++。h不是C++的一部分。 –

+0

...并使用'使用命名空间std;'使它变得更糟 – StoryTeller

+2

'*(stck + top)'这被混淆了。写清楚'stck [top]'而不是 – bolov

回答

0

你的函数pop()方法返回无效数据,并具有负折射率的任何数组访问将是不确定的。正如其他人所说,不要实现自己的堆栈,使用std :: stack和更明显的API。