【发布时间】:2020-04-22 20:51:11
【问题描述】:
我正在尝试查找中缀表达式的后缀形式。我的程序应该在给定的文本文件中读取并计算它。该程序读取文件并向我显示中缀形式,但它不计算中缀表达式的后缀形式。我无法理解问题出在哪里。我的意思是,我不知道问题出在 main() 函数还是 convertToPostfix 函数中。我应该怎么做才能解决这个问题?
主要功能:
int main() {
infixToPostfix<string> exp;
string getcontent;
ifstream infile;
infile.open("infixData.txt");
if (infile.is_open()) {
while (!infile.eof()) {
exp.showInfix();
infile >> getcontent;
cout << getcontent << endl;
exp.convertToPostfix();
exp.getPfx();
exp.showPostfix();
}
}
return 0;
}
还有converToPostfix()函数:
template <class Type>
void infixToPostfix<Type>::convertToPostfix() {
stackType<string> obj;
stackType<char> x;
int i = 0, j=0;
while (infx[i] != '\0')
{
if ((infx[i] >= 'a' && infx[i] <= 'z') || (infx[i] >= 'A' && infx[i] <= 'Z')) {
pfx[j] += infx[i];
}
else if (infx[i] == '('){
obj.push("(");
}
else if (infx[i] == ')') {
while (obj.top() != "(")
{
pfx += obj.top();
obj.pop();
}
if (obj.top() == "(")
obj.pop();
}
else{
while (precedence(x.top(), infx[i]))
{
pfx += obj.top();
obj.pop();
j++;
}
obj.push(infx);
}
i++;
}
cout << pfx << endl;
}
我的“infixData.txt”文件:
A+B-C;
(A+B)*C;
(A+B)*(C-D);
A+((B+C)*(E-F)-G)/(H-I);
A+B*(C+D)-E/F*G+H;
2+4-1;
(6+3)*2;
showInfix():
template <class Type>
void infixToPostfix<Type>::showInfix()
{
cout << endl;
cout << "Infix expression: " << infx;
}
【问题讨论】:
-
当然主要功能很奇怪。您似乎正在将中缀表达式读入一个名为
getcontent的变量中,对吗?但是您的convertToPostfix例程在一个名为infx的变量上运行,并且没有给出如何设置的线索。需要更多代码。以及有关文件 infixData.txt 中内容的详细信息。 -
然后有一个奇怪的方法
showInfix没有给出关于它可能在做什么的线索。总体而言,代码看起来杂乱无章且晦涩难懂,但没有足够的信息来准确诊断问题所在。
标签: c++ class templates postfix-notation infix-notation