Как я могу распечатать этот расчет? Вопрос стека - PullRequest
0 голосов
/ 06 октября 2019

это вопрос структуры данных (стека). в с ++. (без использования STL) я хочу ввести файл формулы Infix (txt, если файла нет, ввод - это ввод текста пользователем.) и преобразовать формулу Postfix, а затем вычислить формулу.

как я могу ввести формулу Postfix в режиме вычисления? Я пытаюсь сделать файл и прочитать файл, но это не работает. (Я пытаюсь изменить конечную позицию (удалить), также не работает.)

ArrayStack.h

#include <iostream>
#include <cstdlib>
#define _CRT_SECURE_NO_WARNINGS

using namespace std;

inline void error(const char *message)

{

    cout << message << endl;

    exit(1);

}



const int MAX_STACK_SIZE = 20;



class ArrayStack

{

private:

    int top;

    int data[MAX_STACK_SIZE];

public:

    ArrayStack()

    {
        top = -1;
    }

    ~ArrayStack()
    {

    }

    bool isEmpty()
    {
        return top == -1;
    }

    bool isFull()
    {
        return top == MAX_STACK_SIZE - 1;
    }

    void push(int e)
    {
        if (isFull())
            error("스택 포화 에러");
        data[++top] = e;
    }

    int pop()
    {

        if (isEmpty())

            error("스택 공백 에러");

        return data[top--];

    }

    int peek()

    {

        if (isEmpty())

            error("스택 공백 에러");

        return data[top];

    }

    void display()

    {
        printf("[스택 항목의 수 = %2d] ==> ", top + 1);
        for (int i = 0; i < top; i++)
            printf("<%2d>", data[i]);
        printf("\n");

    }

};

pg1_stack.cpp

#pragma warning(disable:4996)

#include "ArrayStack.h"
#include <string.h>
#include <fstream>


inline static int precedence(char op)
{
    switch (op) {
    case '(': case ')': return 0;
    case '+': case '-': return 1;
    case '*': case '/': return 2;
    }
    return -1;
}

void infixToPostfix(FILE *fp = stdin)
{
    char         c, op;
    double       val;
    ArrayStack stack;
    ofstream os;
    os.open("stack_Data.txt");

    while ((c = getc(fp)) != '\n')
    {
        if ('0' <= c && c <= '9')
        {
            ungetc(c, fp);
            fscanf_s(fp, "%lf", &val);
            printf("%4.1f ", val);
            os << val;

        }
        else if (c == '(')
            stack.push(c);
        else if (c == ')')
        {
            while (!stack.isEmpty())
            {
                op = stack.pop();
                if (op == '(') break;
                else
                    printf("%c ", op);
                os << op;
            }
        }
        else if (c == '+' || c == '-' || c == '*' || c == '/')
        {
            while (!stack.isEmpty())
            {
                op = stack.peek();
                if (precedence(c) <= precedence(op))
                {
                    printf("%c ", op);
                    os << op;
                    stack.pop();
                }
                else break;
            }
            stack.push(c);
        }
    }
    while (!stack.isEmpty()) {
        char c2 = stack.pop();
        os << c2;

    printf("%c ", c2);
        }os << endl;
os.close();
    printf("\n");

}

double calcPostfixExpr(const char *filename)
{
    FILE *fp = fopen(filename, "r");

    if (fp == NULL)

        error("Error: 파일 존재하지 않습니다.\n");

    char ch;
    ArrayStack stack;

    while ((ch = getc(fp)) != '\n')
    {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
        {
            double right = stack.pop();
            double left = stack.pop();
            switch (ch) {
            case '+':
                stack.push(left + right);
                break;
            case '-':
                stack.push(left - right);
                break;
            case '*':
                stack.push(left * right);
                break;
            case '/':
                stack.push(left / right);
                break;
            }
        }
        else if ('0' <= ch && ch <= '9')
        {
            ungetc(ch, fp);
            double val;
            fscanf_s(fp, "%lf", &val);
            stack.push(val);
        }
    }
    fclose(fp);
    return stack.pop();
}


void main() {

    infixToPostfix();
    double res = calcPostfixExpr("stack_Data.txt");
    printf("%f", res);
    system("Pause");
}

это перед попыткой сделатьфайл и способ чтения файла

#pragma warning(disable:4996)

#include "ArrayStack.h"
#include <string.h>
#include <fstream>


inline static int precedence(char op)
{
    switch (op) {
    case '(': case ')': return 0;
    case '+': case '-': return 1;
    case '*': case '/': return 2;
    }
    return -1;
}

void infixToPostfix(FILE *fp = stdin)
{
    char         c, op;
    double       val;
    ArrayStack stack;

    while ((c = getc(fp)) != '\n')
    {
        if ('0' <= c && c <= '9')
        {
            ungetc(c, fp);
            fscanf_s(fp, "%lf", &val);
            printf("%4.1f ", val);

        }
        else if (c == '(')
            stack.push(c);
        else if (c == ')')
        {
            while (!stack.isEmpty())
            {
                op = stack.pop();
                if (op == '(') break;
                else
                    printf("%c ", op);

            }
        }
        else if (c == '+' || c == '-' || c == '*' || c == '/')
        {
            while (!stack.isEmpty())
            {
                op = stack.peek();
                if (precedence(c) <= precedence(op))
                {
                    printf("%c ", op);
                    stack.pop();
                }
                else break;
            }
            stack.push(c);
        }
    }
    while (!stack.isEmpty()) {
        char c2 = stack.pop();

        printf("%c ", c2);
    }
    printf("\n");

}

double calcPostfixExpr(FILE* fp = stdin)
{

    char ch;
    ArrayStack stack;

    while ((ch = getc(fp)) != '\n')
    {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
        {
            double right = stack.pop();
            double left = stack.pop();
            switch (ch) {
            case '+':
                stack.push(left + right);
                break;
            case '-':
                stack.push(left - right);
                break;
            case '*':
                stack.push(left * right);
                break;
            case '/':
                stack.push(left / right);
                break;
            }
        }
        else if ('0' <= ch && ch <= '9')
        {
            ungetc(ch, fp);
            double val;
            fscanf_s(fp, "%lf", &val);
            stack.push(val);
        }
    }
    return stack.pop();
}


void main() {

    infixToPostfix();
    system("Pause");
}
...