- #include<stdio.h>
- #include<string.h>
- #include<ctype.h>
- #include<stdlib.h>
- #define MAXSIZE 30
- typedef int ElemType;
- typedef struct Stack{ //栈结构
- ElemType data[MAXSIZE];
- int top;//栈顶指针
- }Stack,*pStack;
- void initStack(pStack S){ //初始化栈
- S->top = -1;
- }
- bool push(pStack S,ElemType e){
- if(S->top == MAXSIZE-1){
- puts("栈满");
- return false;
- }
- S->data[++(S->top)] = e;
- return true;
- }
- bool pop(pStack S,ElemType *e){
- if(S->top == -1){
- puts("栈空");
- return false;
- }
- *e = S->data[(S->top)--];
- return true;
- }
- int main(void){
- char string[MAXSIZE];//存储字符串
- char tempNumber[MAXSIZE];//存储数值字符
- char ch;//分解每个字符
- int index;
- int number;//从字符中获得的数值
- int result = 0;//最终结果
- int count = 0;//数字计数
- int a1,a2;//辅助数值计算
- bool tag;//标志位,数字是否已经结束
- Stack numberStack;//数字栈
- pStack S = &numberStack;//指向栈的指针
- initStack(S);//初始化栈
- puts("Enter a string");
- gets(string);
- for(index=0;index<strlen(string);index++){
- ch = string[index];
- if(isdigit(ch)){
- tag = true;//现在输入的是数字
- tempNumber[count] = ch;
- count++;
- }
- else{
- if(tag){ //判断上一个字符是不是数值
- tempNumber[count] = '\0';//一个数值结束了
- number = atoi(tempNumber);
- push(S,number);
- count = 0;//重新计算数值
- tag = false;
- }
- switch(ch){
- case '+':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1+a2);
- break;
- case '-':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1-a2);
- break;
- case '*':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1*a2);
- break;
- case '/':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1/a2);
- break;
- default:
- break;
- }
- }
- }
- pop(S,&result);
- printf("%d",result);
- getchar();
- return 0;
- }