2011-10-25 6 views
0

私はすでに後置記法でそれを持っており、後置記法を持つ文字列変数を送信しています:5 15 2 * + ここに私のコードです:C++でスタックを使用してPostfixの式を評価する

int evaluatePostFix(string postfix_expression){ 
//Create a new stack 
stack<int> theStack; 
//Loops while the postfix expression string still contains values 
while(postfix_expression.length()>=1){ 
    //Loops on a number an whitespace 
    while(isdigit(postfix_expression.at(0)) || isspace(postfix_expression.at(0))){ 
     //Holds a number that is above two digits to be added to the stack 
     string completeNum; 
     if(isdigit(postfix_expression.at(0))){ 
      //Add the digit so it can become a full number if needed 
      completeNum+=postfix_expression.at(1); 
     } 
     else { 
      //Holds the integer version of completeNum 
      int intNum; 
      //Make completeNum an int 
      intNum=atoi(completeNum.c_str()); 
      //push the number onto the stack 
      theStack.push(intNum); 
     } 
     //Check to see if it can be shortened 
     if(postfix_expression.length()>=1){ 
      //Shorten the postfix expression 
      postfix_expression=postfix_expression.substr(1); 
     } 
    } 
    //An Operator has been found 
    while(isOperator(postfix_expression.at(0))){ 
     int num1, num2; 
     char op; 
     //Grabs from the top of the stack 
     num1=theStack.top(); 
     //Pops the value from the top of the stack - kinda stupid how it can return the value too 
     theStack.pop(); 
     //Grabs the value from the top of the stack 
     num2=theStack.top(); 
     //Pops the value from the top of the stack 
     theStack.pop(); 
     //Grab the operation 
     op=postfix_expression.at(0); 
     //Shorten the postfix_expression 
     postfix_expression=postfix_expression.substr(1); 
     //Push result onto the stack 
     theStack.push(Calculate(num1,num2, op)); 
    } 
} 
return theStack.top(); 

}

私が手にエラーがある

私ははるかに高く評価されるだろう、このエラーに取得することができます任意の助けを「のDequeイテレータはdeferencableありません」。 btw私は2,3年でC++を使用していないので、少し錆びています。

+0

'isspace()'を 'isdigit()'と同じように扱っているのはなぜですか?それは私の間違いのようです。 (おそらく、あなたがトリップしたエラーメッセージではありませんが) – sarnold

+0

構文エラーがあったので、すべてのコードを貼り付けましたか?エラーの原因となった行だけを投稿しないのはなぜですか? – Ayjay

+0

Hrmの場合は、文字列の一部を入力として使用した後に文字列を短くすることができるかどうかを確認する必要があります。文字列がスペースまたは数字で終わっていれば、外側の 'while(postfix_expression.length()> = 1)'ループを終了するとは思わない。文字列を減らすことができるかどうかをチェックしないでください。入力を消費したため、サイズを小さくしてください。また、 '12'を入力すると、文字列から1桁だけを取り除くことはできません。 – sarnold

答えて

1

デバッガを使用してステップインしてエラーの原因となっているラインを教えてくれれば簡単です。しかし、私はエラーを発見したかもしれないと思う。あなたはその要素が存在する場合、これまでチェックせずにpostfix_expression.at(1)を求めるコード

if(isdigit(postfix_expression.at(0))){ 
    //Add the digit so it can become a full number if needed 
    completeNum+=postfix_expression.at(1); 
} 

のこのブロックで

。チェックがないので、悪いメモリの場所にアクセスしている可能性があります。

関連する問題