每当我尝试对带有'('的表达式执行此代码片段时,它将显示无休止的循环并最终崩溃。但是对于没有括号的表达式,这件事绝对可以正常工作。下面是相同的代码。
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
int tos=-1;
char stack[100];
void postfix();
void push(char);
char pop();
int precedence(char);
int main()
{
int choice;
char loop;
do{
system("cls");
printf("\n\n\t\t\t1.Infix to Postfix2.Exit\n\n\t\t\tEnter your choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: postfix();
break;
case 2: printf("Thanks for choosing us. ");
system("pause");
exit(1);
default: printf("\n\nInvalid option.");
break;
}
printf("\n\nDo you want to try again(y/n)? ");
loop=getch();
}while(loop!='n');
return 0;
}
void postfix()
{
int i;
char infix[100], temp;
printf("\n\nEnter the infix expression: ");
scanf("%s", infix);
printf("\n\nPostfix expression: ");
for(i=0; i<=strlen(infix)-1; i++)
{
if(isalnum(infix[i]))
printf("%c", infix[i]);
else
{
if(tos==-1)
{
push(infix[i]);
}
else if(infix[i]!=')')
{
if(precedence(stack[tos])>=precedence(infix[i]))
{
while(precedence(stack[tos])>=precedence(infix[i]))
{
printf("%c", pop());
}
push(infix[i]);
}
else
{
push(infix[i]);
}
}
else
{
temp=pop();
while(temp!='(')
{
printf("%c", temp);
temp=pop();
}
}
}
}
while(tos>-1)
{
printf("%c", pop());
}
printf("\n\nStack: %s", stack);
}
void push(char x)
{
stack[++tos]=x;
}
char pop()
{
return stack[tos--];
}
int precedence(char sign)
{
if(sign=='+'||sign=='-')
return 1;
else if(sign=='*'||sign=='/')
return 2;
else if(sign=='^')
return 3;
else
return 0;
}
但是,如果我删除优先级比较部分中的while代码,则会给出不崩溃的错误输出。