#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int PrintError = 0;
/*全局变量,0代表正常,1代表表达式出错*/
/*char类型链表式堆栈,用来存放运算符号,以及用在中缀表达式转换等时候*/
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack S);
void MakeEmpty(Stack S);
void Push(char X,Stack S);
char Top(Stack S);
void Pop(Stack S);
typedef struct Node{
char Element;
PtrToNode Next;
};
/*float类型链表式堆栈,用来存放操作数*/
typedef struct FNode *Ptr_Fn;
typedef Ptr_Fn FStack;
int FisEmpty(FStack S);
void FPush(float X,FStack S);
float FTop(FStack S);
void FPop(FStack S);
typedef struct FNode{
float Element;
Ptr_Fn Next;
};
void ConvertToPost(FILE *In, Stack Whereat,FILE *Temp);
void Reverse(Stack Rev);
void Calculate(FILE *Change, Stack Whereat,FILE *Temp);
/******主函数******/
int main()
{
FILE *InputFile, *OutputFile,*Temp; /*初始化变量*/
Stack Whereat;
char sample;
InputFile = fopen("Input.txt","r"); /*打开文件*/
OutputFile = fopen("Output.txt","w");
Whereat = malloc(sizeof(struct Node)); /*给 Whereat分配空间*/
Whereat->Next = NULL;
if (!InputFile || !OutputFile) { /*错误处理*/
printf("intput or output file(s) do not exist.\n");
return(1);
}
sample = getc(InputFile);
while ( sample != EOF){
Temp = fopen("Temp.txt","w+"); /*生成Temp文件*/
ungetc(sample,InputFile); /* put back sample字符*/
ConvertToPost(InputFile,Whereat,Temp); /*中缀变后缀*/
if (PrintError){ /*错误处理*/
fprintf(OutputFile,"Error in infix notation.");
fscanf(InputFile,"\n",&sample);
PrintError = 0;
}
else if (IsEmpty(Whereat) == 1){ /*跳过在input文件中的空格*/
}
else if (IsEmpty(Whereat) != 1){
Reverse(Whereat);
if (Top(Whereat) == 'B'){ /*错误处理,*/
/*A表示操作数B表示运算符*/
PrintError = 1; /*后缀表达式第一个元素应是操作数而不是运算符号*/
}
fclose(Temp);
Temp = fopen("Temp.txt","r+");
Calculate(OutputFile, Whereat,Temp); /*计算结果*/
}
fclose(Temp);
MakeEmpty(Whereat); /* 清空Whereat用来处理下一行*/
putc('\n',OutputFile); /* 在输出文件中换行*/
sample = getc(InputFile);
}