使用堆栈中缀到postfix转换

时间:2014-03-20 10:39:38

标签: c bash postfix-notation infix-notation

我编写了将中缀符号转换为后缀的代码。它没有括号工作正常,但当我将表达式括在括号中时,给我一个运行时错误。我要使用命令行参数。

#include<stdio.h>
int top = -1;
push(char *s, char elem) {
  ++top;
  s[top] = elem;
}

char pop(char *s) { 
 char elem;
  elem = s[top];
  top--;
  return (elem);
 }

int Sempty() { 
 if (top == -1)
  return 1;
 return 0;
}

int pri(char elem){
switch(elem){
case '/':
case '*':   return 2;
case '+':
case '-':   return 1;
}   }

main(int argc, char *argv[]){
int i, x, y;
char elem, new;
char a[50];
printf("\t\t------infix notation-----\n");
for(i = 1; i<argc; i++) printf("%s ", argv[i]);
printf("\n\t\t------postfix notation-----\n");
for(i = 1; i<argc; i++){
if(argv[i][0] == '(')   push(a, argv[i][0]);
else if(isalnum(argv[i][0]))    printf("%s ", argv[i]);
else if(argv[i][0] == ')'){ elem = pop(a);
    while(elem != '('){
        printf("%c ", elem);
        elem = pop(a);  }
    if(elem == '(') top--;
        }
else{
x = pri(argv[i][0]);
    if(Sempty())    push(a, argv[i][0]);
    else{
    elem = pop(a);
    y = pri(elem);
        if(y>=x){
            printf("%c ", elem);
            push(a, argv[i][0]);    }
        else{ 
            push(a, elem);  
            push(a, argv[i][0]);}
        }   }
}
while(!Sempty()){
elem = pop(a);
printf("%c ", elem);    }
printf("\n");
}

输入

./a.out 2 + 3

输出

------infix notation-----
2 + 3 

------postfix notation-----

2 3 + 

但如果我给予

输入

./a.out ( 2 + 3 )

输出

bash: syntax error near unexpected token `2'

1 个答案:

答案 0 :(得分:2)

括号对shell有特殊意义,你必须引用或转义它们:

./a.out '(' 2 + 3 ')'