gpt4 book ai didi

c++ - 后缀符号 C++ 的中缀

转载 作者:行者123 更新时间:2023-11-28 07:31:49 25 4
gpt4 key购买 nike

<分区>

Hello Stack 我目前正在尝试编写一个 RPN 转换器,我是 C++ 的新手。但是我遇到了问题。希望我能详细解释这些问题。我正在使用一个数组来堆叠我的运算符。让我们使用示例“5 + 8”当我开始:

else if(infix[i] == '+' or infix[i] == '-' or infix[i] == '*' or infix[i] == '/' or infix[i] == '^'){
while(isp(stack1.top()) >= icp(infix[i])){
postfix += stack1.pop();
}
if(isp(stack1.top()) < icp(infix[i])){
stack1.push(infix[i]);
}

出于某种原因,它会将运算符压入堆栈,但不会将运算符添加到我也添加我的元素的后缀字符串变量中。输出会像“5 8” 我查看了我的 pop 函数,这似乎是正确的,但我很难过。如果你能引导我朝着正确的方向前进,那就太好了。

这是我的完整代码:

#include <iostream>
#include <string>
#define DEFAULT_SIZE 100

using namespace std;

class Stack{

private:
char *array;
int tos, capacity;

public:
//constructors
Stack();

//Destructor
~Stack();

//Methods
void push(char a);
char pop();
char top();
int get_size();
bool is_empty();
bool is_full();
void display();

};

Stack::Stack(){
array = new char[DEFAULT_SIZE];
tos = 0;
capacity = DEFAULT_SIZE;
}

Stack::~Stack(){
delete[] array;
}

void Stack::push(char a){
if(!is_full())
array[tos++] = a;
}

char Stack::pop(){
return array[--tos];
}

char Stack::top(){
return array[tos];
}

int Stack::get_size(){
return tos;
}

bool Stack::is_empty(){
if(tos == 0)
return true;
else
return false;
}

bool Stack::is_full(){
if(tos == capacity)
return true;
else
return false;
}

void Stack::display(){
if (tos == 0)
cout<<"The stack is empty"<<endl;
else{
for (int i=0; i<tos;i++)
cout<<array[i]<<" ";
cout<<endl;
}
}

int isp(char a){
if(a == '^'){
return 3;
}
else if (a == '*' or a == '/'){
return 2;
}
else if(a == '+' or a == '-'){
return 1;
}
else if(a == '('){
return 0;
}
else
return -1;
}

int icp(char a){
if(a == '^'){
return 4;
}
else if (a == '*' or a == '/'){
return 2;
}
else if(a == '+' or a == '-'){
return 1;
}
else if(a == '('){
return 4;
}
}



int main(){
string infix, postfix;
Stack stack1;

cout << "This is a Infix to Postfix Expression converter." << endl;
cout << "Enter your Infix Expression: ";
cin >> infix;
stack1.push('#');

for(int i=0;i<infix.length();i++){
if(isdigit(infix[i]) or isalpha(infix[i])){
postfix += infix[i];
}
else if(infix[i] == '+' or infix[i] == '-' or infix[i] == '*' or infix[i] == '/' or infix[i] == '^'){
while(isp(stack1.top()) >= icp(infix[i])){
postfix += stack1.pop();
}
if(isp(stack1.top()) < icp(infix[i])){
stack1.push(infix[i]);
}
}
}
cout << postfix;


return 0;
}

此外,如果您知道有关 C++ RPN 转换器的任何好的资源站点,请随时分享,因为这将是一个非常大的帮助!我正在进行随机算法。我在谷歌上找到的。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com