![](/img/trans.png)
[英]I have written this code to convert an infix expression to a postfix expression using Stacks in CPP
[英]I have written this program for infix to postfix conversion
#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()
,或者在遇到换行符时停止处理循环。
尝试将fgets
更改为std::cin
。 并使用std::string
代替char*
:
#include <iostream>
#include <string>
int main()
{
string exp;
cout << "Enter expression: ";
std::cin >> exp;
auto t = exp.data();
char x;
for(auto &ch: exp)
{
if(isalnum(ch))
cout << ch;
else if(ch == '(')
push(ch);
else if(ch == ')')
{
while((x = pop()) != '(')
cout << x;
}
else
{
if(priority(stk[top]) >= priority(ch))
cout << pop();
push(ch);
}
}
while(top != -1)
cout << pop();
return 0;
}
除了NathanOliver提到的'\\n'
处理之外,当用户输入了if
语句中未检查的任何其他字符时,函数priority()
不会返回值,因此该行为可能是不确定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.