2012-04-19 119 views
0

我試圖從txt文件讀取後綴表達式並評估它 輸入是10 5 *,輸出應該是50,但它只讀取10和5, 他無法讀取運營商沒有ascii代碼,有什麼幫助? 這裏是我的代碼使用堆棧後綴評估

#include <iostream> 
#include <iomanip> 
#include <fstream> 
#include<stdio.h> 
#include<ctype.h> 
#include<stdlib.h> 
using namespace std; 
#define SIZE 40 
int stack[SIZE]; 
int top=-1; 

void push(int n) 
{ 
    if(top==SIZE-1) 
    { 
     printf("Stack is full\n"); 
     return; 
    } 
    else 
    { 
     top=top+1; 
     stack[top]=n; 
     printf("Pushed element is %d\n",n); 
     system("pause"); 
    } 
} 

int pop() 
{ 
    int n; 
    if(top==-1) 
    { 
     printf("Stack is empty\n"); 
     system("pause"); 
     return 0; 
    } 
    else 
    { 
     n=stack[top]; 
     top=top-1; 

     return(n); 
    } 
} 

int main() 
{ 

    int str[50],ch; 

    int i=0; 
    int n,op1,op2; 

    ifstream inFile; 
    ch=str[i]; 

    inFile.open("D:\\me.txt"); 
    if (!inFile) 
    { 
     printf("Unable to open file"); 
     system("pause"); 
     exit(1); // terminate with error 
    } 

    while (inFile >> ch) 
    { 
     if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='%' || ch=='^') 
     { 

      op1=pop(); 
      op2=pop(); 
      if (op1<op2) 
      { 
       n=op1; 
       op1=op2; 
       op2=n; 
      } 
      if(ch=='+') 
       n=op1+op2; 
      else if(ch=='-') 
       n=op1-op2; 
      else if(ch=='*') 
       n=op1*op2; 
      else if(ch=='/') 
       n=op1/op2; 
      else if(ch=='%') 
       n=op1%op2; 
      else if(ch=='^') 
       n=op1^op2; 
      else 
      { 
       printf("The operator is not identified\n"); 
       system("pause"); 
       exit(0); 
      } 

      printf("n=%d\n",n); 
      system("pause"); 
      push(n); 


     } 
     else 
     { 
      n=ch; 
      push(n); 
     } 
     ch=str[++i]; 
    } 
    inFile.close(); 
    printf("The value of the arithmetic expression is=%d\n",pop()); 
    system("pause"); 
    return 0; 
} 

回答

1

的問題是,chint所以inFile >> ch將只讀取nummbers - 在'*'字符被忽略。

而且,你有一個str[]數組是未初始化您定期讀出分配給ch(那麼你忽略任何剛剛寫入ch)。你需要擺脫str[]或完成讓你把它放在第一位的想法...