【问题标题】:postfix evaluation using stack使用堆栈的后缀评估
【发布时间】:2012-05-01 04:11:36
【问题描述】:

我正在尝试从 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;
} 

【问题讨论】:

    标签: c++ file stack postfix-notation


    【解决方案1】:

    问题在于chint,所以inFile &gt;&gt; ch 只会读取数字-'*' 字符被忽略。

    另外,您有一个未初始化的 str[] 数组,您会定期读出该数组以分配给 ch(然后您忽略刚刚写入 ch 的任何内容)。你需要摆脱str[] 或者完成让你把它放在那里的想法......

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 2011-08-03
      • 2015-05-03
      • 1970-01-01
      • 2014-07-01
      • 2011-12-14
      • 2013-10-11
      • 2015-02-14
      相关资源
      最近更新 更多