繁体   English   中英

如何从C++中的函数返回字符串

[英]how to return string from function in c++

我编写了一个 C++ 代码,使用堆栈将中表达式转换为后缀表达式,但是每当我尝试从堆栈中返回弹出的值时,它都不会返回字符串。返回的字符串为空,而不是堆栈的原始内容。 我需要先把它转换成char吗? 强文本

输入:A+B

输出:AB

正确输出:AB+

如何从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;
}

当 top==0 时,您的函数 pop() 返回无效数据,因为您在索引堆栈之前减少了 top,并且任何具有负索引的数组访问都将是未定义的。 正如其他人所说,不要实现自己的堆栈,使用 std::stack 和更明显的 api。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM