我正在编写将中缀表示法转换为后缀表示法的代码。它可以成功编译,但是当我运行它时,它将引发一些异常。我不明白为什么会引发异常。
#include<iostream>
#include<fstream>
using namespace std;
const int MAX = 20;
class stack
{
char st[MAX];
int top;
public:
stack() {
top = -1;
}
void push(char ch)
{
if (top == MAX - 1)
{
cout << "STACK IS FULL! ";
return;
}
st[++top] = ch;
}
char pop()
{
if (top == -1)
{
cout << "STACK IS EMPTY! ";
return NULL;
}
return st[top--];
}
char showtop()
{
return st[top];
}
bool isempty()
{
if (top == -1)
return true;
return false;
}
};
int main()
{
char infix[MAX] = { 0 }, postfix[MAX] = { 0 };
stack obj;
int j;
ifstream infile;
infile.open("infixexpr1.txt", ios::in);
if (infile.is_open())
cout << "open";
infile >> infix;
infile.close();
for (int i = 0; i < strlen(infix); i++)
{
if (infix[i] == '+' || infix[i] == '-')
{
while ((!obj.isempty()) && (!obj.showtop() == '('))
postfix[j++] = obj.pop();
obj.push(infix[i]);
}
else if (infix[i] == '*' || infix[i] == '/')
{
if (obj.showtop() == '*' || obj.showtop() == '/' || obj.showtop() == '^')
postfix[j++] = obj.pop();
obj.push(infix[i]);
}
else if (infix[i] == '^')
{
if (obj.showtop() == '^')
postfix[j++] = obj.pop();
else
obj.push(infix[i]);
}
else if (infix[i] == '(')
obj.push(infix[i]);
else if (infix[i] == ')')
{
while (obj.showtop() == '(')
postfix[j++] = obj.pop();
obj.pop();
}
else
postfix[j++] = infix[i];
}
while (!obj.isempty())
postfix[j++] = obj.pop();
cout << "POSTFIX EXPRESSION! ";
cout << postfix;
system("pause");
return 0;
}
我已经在程序目录中创建了一个文件,并将其中的字符串读取到infix
字符数组中。当我运行程序时,它将引发异常。