[ create a new paste ] login | about

Link: http://codepad.org/TIGEcjYN    [ raw code | output | fork ]

C, pasted on Oct 31:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* s;

int E(int);
int T(int);
int F();
int E(int l){
	while(1){
		if(*s=='+'){
			s++; l+=T(F());printf("+"); continue;
		}else if(*s=='-'){
			s++; l-=T(F());printf("-");continue;
		}
		break;
	}
	return l;
}
int T(int l){int r;
	while(1){
		if(*s=='*'){s++;
			l*=F();printf("*");continue;
		}else if(*s=='/'){s++;
			r=F();if(!r){puts("divide by zero");exit(1);}
			l/=r;printf("/");continue;
		}
		break;
	}
	return l;
}
int F(){int l;
	if('0'<=*s&&*s<='9'){
		printf("%c",*s);
		l= *s-'0'; s++; return l;
	}else if(*s=='('){
		s++;l=E(T(F())); if(*s!=')'){puts("paren match error");exit(1);}
		s++;return l;
	}else{
		puts("error");exit(1);
	}
}


int main(int argc, char *argv[])
{
	char* str = "5+3*2-(4*(6-4))";
	s=str;
	printf("infix: %s\n",str);
	printf("postfix: ");
	printf("\n = %d\n",E(T(F())));

	return 0;
}


Output:
1
2
3
infix: 5+3*2-(4*(6-4))
postfix: 532*+464-*-
 = 3


Create a new paste based on this one


Comments: