如何在 C++ 中从函数返回字符串
how to return string from function in c++
我编写了一个 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。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量