简体   繁体   English

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

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

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.我编写了一个 C++ 代码,使用堆栈将中表达式转换为后缀表达式,但是每当我尝试从堆栈中返回弹出的值时,它都不会返回字符串。返回的字符串为空,而不是堆栈的原始内容。 Do I need to convert it into char first?我需要先把它转换成char吗? strong text强文本

input: A+B输入:A+B

output: AB输出:AB

correct output: AB+正确输出:AB+

How to return string from member function in c++?如何从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.当 top==0 时,您的函数 pop() 返回无效数据,因为您在索引堆栈之前减少了 top,并且任何具有负索引的数组访问都将是未定义的。 As others have said, don't implement your own stack, use std::stack and more obvious api's.正如其他人所说,不要实现自己的堆栈,使用 std::stack 和更明显的 api。

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

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