使用堆栈的后缀评估 [英] postfix evaluation using stack

查看:72
本文介绍了使用堆栈的后缀评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从txt文件读取后缀表达式并对其进行评估
输入为10 5 *,输出应为50,但它只能读取10和5,错误在哪里?
这是我的代码

Hi, i''am trying to read postfix expression from txt file and evaluate it
the input is 10 5 * ,the output should be 50, but it reads only 10 and 5, where''s the error?
here''s my code

#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");
  system("pause");
 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==43 || ch==45 || ch==47 || ch==42 || ch==94 || ch==37 )
 {

	 op1=pop();
	 op2=pop();
	 if (op1<op2)
	 {
	 n=op1;
	 op1=op2;
	 op2=n;
	 }
	 switch(ch)
	 {
	 case 43:
	 n=op1+op2; break;
	 case 45:
	 n=op1-op2;break;
	 case 42:
	 n=op1*op2;break;
	 case 47:
	 n=op1/op2;break;
	 case 37:
	 n=op1%op2;break;
	 case 94:
	 n=op1^op2;break;
	
 
	 default:
	 {
	 printf("The operator is not identified\n");
	 system("pause");
	 exit(0);break;
	 }
	 }
	 printf("n=%d\n",n);
	 push(n);
	 system("pause");


 }
	 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;
 } 

推荐答案

首先,请删除该代码并正确缩进-这样每个人都可以轻松地看到发生了什么.然后添加一些评论.然后用常量名称或实际字符替换您的幻数.其中哪个更容易阅读和理解:
irst off, take that code and indent it properly - so everyone can see easily what is going on. Then add some comments. Then replace your magic numbers with constant names, or the actual characters. Which of these is easier to read and understand:
if (ch == 42)


if (ch == '+')


if (ch == OPERATOR_ADD)


然后,我们可以更轻松地解决问题.

但我会给您一个提示:查看输入字符串中的内容,并查看您在堆栈中压入和弹出的内容.您从文件中得到什么字符?如果您的代码有效,您将添加什么值?您要堆放多少物品?


Then we can look at the problem a lot more easily.

But I''ll give you a hint: Look at what is in your input string, and also look at what you push and pop on the stack. What characters are you getting from the file? What values would you be adding if your code worked? How many items are you putting on the stack?


这篇关于使用堆栈的后缀评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆