#include<iostream>
#include<stdio.h>
#define MAX 20
using namespace std;
char stk[MAX];
int top=-1;
void push(char c)
{
if(top==MAX-1)
cout<<"Overflow";
else
{
stk[++top]=c;
}
}
char pop()
{
if(top==-1)
{
return '\0';
}
else
return stk[top--];
}
int priority(char ch)
{
if(ch=='(')
return 1;
if(ch=='+'||ch=='-')
return 2;
if(ch=='*'||ch=='/')
return 3;
if(ch=='^')
return 4;
}
int main()
{
char exp[35],*t,x;
cout<<"Enter expression: ";
fgets(exp,35,stdin);
t=exp;
while(*t)
{
if(isalnum(*t))
cout<<*t;
else if(*t=='(')
push(*t);
else if(*t==')')
{
while((x=pop())!='(')
cout<<x;
}
else
{
if(priority(stk[top])>=priority(*t))
cout<<pop();
push(*t);
}
t++;
}
while(top!=-1)
cout<<pop();
return 0;
}
输入的输出:
a+b-(c+d/e)
是
ab+cde/+
-
我不明白为什么 - 在换行符上。 我刚开始学习 c++,我正在尝试使用 c++ 实现我在 c 中所做的一些程序。 c 中的相同代码工作正常。我认为我的基本 C++ 知识有一些漏洞,我想填补它们。
最佳答案
std::fgets
不会像 getline
那样丢弃输入流中的换行符。这意味着 exp
包含 "a+b-(c+d/e)\n"
而不是 "a+b-(c+d/e) “
。您需要从 exp
中删除换行符,切换到 cin.getline()
,或者在遇到换行符时停止处理循环。
关于c++ - 我写了这个程序用于中缀到后缀的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634582/