令我惊讶的是,我的代码运行良好!! 唯一的问题是,每当我使用带括号的中缀输入时,它都会在后缀表达式的末尾出现一个“J”!!有什么建议么?? 这里的算法是基本算法,所有表达式都已转换,一切都正确,但尾部“J”是我无法理解的!!建议??
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAX 50
char stack[MAX];
int top = -1;
void push(char element)
{
stack[++top] = element;
}
char pop()
{
return(stack[top--]);
}
char tope()
{
return(stack[top]);
}
int prec(char c)
{
switch(c){
case '+':
case '-' : return 1;
break;
case '*' :
case '/' : return 2;
break;
default:
return 0;
break;
}
}
int main()
{
char post[MAX],in[MAX],ch,element;
printf("Infix expression : ");
scanf("%s",in);
int i=0,k=0;
in[strlen(in)] = ')';
push('(');
while((ch = in[i++]) != '\0')
{
if(isalnum(ch))
post[k++] = ch;
if(ch == '(')
push(ch);
if(ch == ')')
{
while(tope() != '(')
{
post[k++] = pop();
}
pop();
}
if(ch == '+' || ch =='-' || ch == '*' || ch == '/')
{
while(prec(ch) <= prec(tope()))
{
post[k++] = pop();
}
push(ch);
}
}
post[k] = '\0';
printf("%s",post);
return 0;
}
最佳答案
in[strlen(in)] = ')';
覆盖 nul 终止字符,这在打印时解释了奇怪的字符(仅当幸运遇到另一个 nul 字符时打印停止:未定义的行为,如果在 中未找到 nul 字符,甚至可能导致崩溃
50 字节缓冲区)
你必须改变它,例如像这样:
int l = strlen(in);
in[l] = ')';
in[l+1] = '\0';
注意:您必须将字符串的长度存储在l
中,而不是调用strlen(in)
两次,这不仅是因为性能损失,但是,因为放置括号意味着 strlen
在您以 null 终止之前无法正常工作。
(您可能还想像这样保护您的 scanf
:scanf("%48s",in);
所以您肯定有足够的空间50 大小缓冲区的额外括号,甚至与您的宏定义兼容,请参阅 scanf: template with macro (#define constant) inside )
关于c - 堆栈中缀到后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435610/