2016-05-06 16 views
0
#include <cctype> 
#include <fstream> 
#include <iostream> 
#include <string> 
#include <stack> 

using namespace std; 

void interpretExpressionFile(string filepath) 
{ 

    // Declare a stack of ints 
    stack<int>myStack; 

    while (true) 
    { 
     char ch; 
     fin >> ch; 

     if (fin.eof()) 
     { 
      break; 
     } 

     if (isspace(ch)) 
     { 
      continue; 
     } 

     if (isdigit(ch)) 
     { 
      int value = (ch - '0'); 

      // Push value onto the stack: 
      myStack.push(value); 
     } 
     else 
     { 

この2つのTODOの下に問題があります。私はこの時点で何が必要かを知っていますが、プログラムが-1を出力し続けるので、私は問題を抱えています。C++スタック。トップ値を削除して変数に配置する

 // TODO: Remove top value from the stack placing it into value2 
      myStack.pop(); 
      int value2 = -1; 

      // TODO: Remove top value from the stack placing it into value2 
      myStack.pop(); 
      int value1 = -1; 

      int result; 
      switch (ch) 
      { 
       case '+': result = value1 + value2; break; 
       case '-': result = value1 - value2; break; 
       case '*': result = value1 * value2; break; 
       case '/': result = value1/value2; break; 
       default: cout << "Unexpected operator: " << ch << endl; return; 
      } 

      // TODO: Push the value in variable result back onto the stack: 
      myStack.push(result); 
     } 
    } 

    fin.close(); 

ここに他の問題があります。これは私が混乱していると思うところです。

// TODO: pop the top value off of the stack placing it into varresult: 
    myStack.pop(); 
    int result = -1; 
    cout << filepath << " - result is: " << result << endl; 
} 

int main() 
{ 
    interpretExpressionFile("expression1.txt"); 
    interpretExpressionFile("expression2.txt"); 
    interpretExpressionFile("expression3.txt"); 
} 

答えて

2

あなたは、stack::top()を使用し、その後、スタックの一番上にある値を得ることはありませstack::pop()、その後スタックから先頭の要素を削除するには、その後pop()呼び出したい場合。だから、あなたはそうするでしょう:

int result2 = myStack.top(); 
myStack.pop(); 
関連する問題