[英]C++ Postfix Expressions Using Stacks
我正在开发一个程序,用于为我的计算机科学课程之一计算后缀表达式的结果。 该程序使用堆栈ADT完成此操作。
我已经编写了程序,但是相信可能会出现错误,因为某些表达式的结果不正确。 我不确定我的错误在哪里。
另外,当输入文件为空时,程序将生成一个值32767。它来自哪里?
表达式:3 4 + 3 *值= 21。
表达式:5 4 3 2 1-+ / *值=0。(应为5)
表达式:9 5 2 4 +-2 * *值=18。(应为-18)
头文件:
#ifndef STACK_H
#define STACK_H
#include <cstdlib>
#include <iostream>
class Stack
{
public:
typedef int Item;
static const int CAPACITY = 50;
// Constructor
Stack() { used = 0; }
// Modification Member Functions
void push(Item entry) {
data[used] = entry;
++used;
}
Item pop() {
if(!empty())
{
--used;
return data[used];
}
}
// Constant Member Functions
bool empty() const { return used == 0; }
int size() const { return used; }
private:
// Data Members
Item data[CAPACITY];
int used;
};
#endif
主程序:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "stack.h"
using namespace std;
int main()
{
Stack s;
string input;
ifstream infile;
int final, operand1, operand2, result;
char infile_name[80];
cout << "Enter input file name: ";
cin >> infile_name;
cout << endl;
infile.open(infile_name);
while(!infile)
{
cout << "Could not open file." << endl;
return 0;
}
while (!infile.eof())
{
getline(infile, input);
cout << "Expression: ";
for (int i = 0; i < input.length(); i++)
{
cout << input[i];
if(input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' || input[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
s.push(input[i] - '0');
if(input[i] == '+')
s.push(s.pop() + s.pop());
if(input[i] == '-')
s.push(s.pop() - s.pop());
if(input[i] == '*')
s.push(s.pop() * s.pop());
if(input[i] == '/')
s.push(s.pop() / s.pop());
}
final = s.pop();
cout << endl << "Value = " << final << "." << endl << endl;
}
}
一个问题是,在语句s.pop() - s.pop()
(以及相类似的除法)中,不能保证首先调用哪个s.pop()
。 因此,从堆栈中删除内容的顺序不一致。 您应该将其作为两个单独的调用进行。
auto oper1 = s.pop();
auto oper2 = s.pop();
s.push(oper1-oper2);
您的错误结果是由于这两种情况下执行的顺序错误而导致的。
像while (!infile.eof())
这样的代码实际上总是错误。 它通常看起来会读取两次输入的最后一项(尽管即使那是不可靠的)。
首先更改:
while (!infile.eof())
{
getline(infile, input);
至:
while (getline(infile, input))
看看效果是否更好。
还要注意,如果堆栈为空,则您的stack.pop()
不会返回值:
Item pop() {
if (!empty())
{
--used;
return data[used];
}
}
如果(例如)您有额外的运算符,那么您将尝试在实际未返回值的情况下使用该值,从而导致未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.