@Author: 张海拔
@Update: 2014-01-12
@Link: http://www.cnblogs.com/zhanghaiba/p/3516660.html
1 /* 2 *Author: ZhangHaiba 3 *Date: 2014-1-12 4 *File: dc_linux.c 5 * 6 *a demo shows how to use a stack to implement dc which as a built-in tool in Linux 7 *but, this demo only support int number and int operation + - * / 8 */ 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <ctype.h> 13 #define ST_LEN 1024 //the depth of stack 14 #define BUF_SIZE 32 15 #define NUM '0' 16 17 //public from stack.h 18 void push(int); 19 int pop(); 20 int top(); 21 int is_empty(); 22 int is_full(); 23 void clear(); 24 //private form stack.c 25 int stack[ST_LEN]; 26 int sp = 0; //point to next empty space 27 28 //public form main.h 29 int token(); 30 //public form main.c 31 char buf[BUF_SIZE]; 32 int cnt = 0; 33 34 int main(void) 35 { 36 int c; 37 int op2, op1; 38 39 while ((c = token()) != EOF) { 40 switch(c) { 41 case NUM: 42 push(atoi(buf)); 43 break; 44 case '+': 45 if (size() >= 2) { 46 op2 = pop(), op1 = pop(); 47 push(op1 + op2); 48 } else 49 printf("dc: stack empty "); 50 break; 51 case '-': 52 if (size() >= 2) { 53 op2 = pop(), op1 = pop(); 54 push(op1 - op2); 55 } else 56 printf("dc: stack empty "); 57 break; 58 case '*': 59 if (size() >= 2) { 60 op2 = pop(), op1 = pop(); 61 push(op1 * op2); 62 } else 63 printf("dc: stack empty "); 64 break; 65 case '/': 66 if (size() >= 2) { 67 op2 = pop(), op1 = pop(); 68 push(op1 / op2); 69 } else 70 printf("dc: stack empty "); 71 break; 72 case 'p': 73 printf(is_empty() ? "dc: stack empty " : "%d ", top()); 74 default: 75 break; 76 } 77 } 78 return 0; 79 } 80 81 int token() 82 { 83 int c = getchar(); 84 if (isdigit(c)) { 85 buf[cnt++] = c; 86 while ((c = getchar()) != EOF) { 87 if (isdigit(c)) 88 buf[cnt++] = c; 89 else { 90 buf[cnt] = '