在文本文件中查找后缀表达式的后缀形式

问题描述 投票:0回答:1

我正在尝试查找中缀表达式的后缀形式。我的程序应在给定的文本文件中读取并计算它。该程序读取文件并向我显示中缀形式,但是它不计算中缀表达式的后缀形式。我不明白问题出在哪里。我的意思是,我不知道问题出在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;

}
c++ class templates postfix-notation infix-notation
1个回答
0
投票

因此,这似乎是代码组织的问题。您只是没有以可能可行的方式使用程序中的变量。您正在将文件读入一个变量,但是使用完全不同的变量来尝试解决问题。

这是您应该做的,将infix表达式读入main中的一个变量中,您将该变量作为参数传递到计算后缀表达式的函数。像这样

        infile >> getcontent;
        cout << getcontent << endl;
        convertToPostfix(getcontext);

然后convertToPostfix应该是看起来像这样的函数

void convertToPostfix(const std::string& infx) {
    ...
}

不需要一个名为infixToPostfix的类,只需编写函数即可完成工作,而不是类。

您确实需要了解有关如何编写函数,如何将参数传递给函数以及从函数返回值的信息。这是一项非常基本的技能。目前您显然还不了解它,但是绝对重要。

您的代码还包含许多高级功能,如类和模板,对于此任务是不必要的,在您尚未掌握基础知识的情况下,无论如何都不应使用它们。

© www.soinside.com 2019 - 2024. All rights reserved.