我正在尝试从文本文件中读取中缀表达式,然后将它们转换为后缀并对其进行评估,一切正常,直到我到达第一个while循环。表达式被转换但是在评估发生之前我一直停留在循环中。有谁知道为什么?我确信这是我想念的小事。
以下是代码:
.form-right{
width: 100% !important;
justify-content: flex-end !important;
}
以下是输入值:
2 + 4 * 8/2 (100 + 200)/ 3
这是我现在得到的输出:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define RogueValue -99
typedef struct Stack {
int top;
char ST[50];
}Stack;
Stack S;
int convertToPostfix(char infx[], char pofx[]);
char push(char ch);
char pop();
int isEmpty();
int precedence(char ch);
void printPostfix(char pofx[], int n);
int evaluate(char infx[], int size);
int main(void) {
FILE * f = fopen("2542.txt", "r"); //opening the input file
char infx[50], pofx[50];
S.top = -1;
fscanf(f, "%s", infx);
while(strcmp(infx,"\n")!= 0) //?????????
{
convertToPostfix(infx, pofx);
printf("Infix Expression: %s\n", infx);
printf("\nPostfix Expression: %s\n\n\n",pofx);
}
fclose(f);
}
int convertToPostfix(char infx[], char pofx[]){
char ch;
int i= 0, k = 0;
while((ch = infx[i++]) != '\0') {
if( ch == '(')
push(ch);
else if(ch >='0' && ch <= '9')
pofx[k++]=ch;
else if( ch == ')') {
while( S.ST[S.top] != '(')
pofx[k++]=pop();
ch = pop();
}
else {
while( precedence(S.ST[S.top]) >= precedence(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( S.ST[S.top] != -1) /* Pop from stack till empty */
pofx[k++]=pop();
return k;
}
char push(char ch) {
if (S.top == 50 - 1){
printf("Stack overflow\n");
return 1;
}
S.ST[++S.top] = ch;
}
char pop() {
if (isEmpty(S))
return RogueValue;
char popped = S.ST[S.top];
--(S.top);
return popped;
}
int isEmpty(){
return(S.top == -1);
}
int precedence(char ch){
if ( ch == '(') return 1;
if ( ch == '+' || ch == '-') return 2;
if ( ch == '*' || ch == '/' || ch == '%') return 3;
if ( ch == '^') return 4;
if ( ch == 'f') return 5;
}
int evaluate (char pofx[], int size){
int i, a , b, c, n;
Stack temp;
S.top = -1; //init Stack
for(i = 0; i < size; i++){
if( pofx[i] <= '9' && pofx[i] >= '0')
push (pofx[i] - '0');
else {
b = pop();
a = pop();
if (pofx[i] == '+')
c = a + b;
else if (pofx[i] == '-')
c = a - b;
else if (pofx[i] == '*')
c = a * b;
else if (pofx[i] == '/')
c = a / b;
else if (pofx[i] == '%')
c = a % b;
else if (pofx[i] == '^'){
c = 1.0;
for(n = 1; n <= b; n++)
c = c*a;
}
else if (pofx[i] == 'f'){
for(n = pofx[i]; n > 0; n--)
c = c*n;
}
push(c);
}
}
return pop();
}
.........
非常感谢任何帮助!