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

how to return string from function in c++

本文关键字:函数 返回 字符串 C++      更新时间:2023-10-16

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

输入: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。