<소스 코드>

#define _CRT_SECURE_NO_WARNINGS

#include "ArrayStack.h"

#include <stdio.h>


//객체의 우선순위 계산

inline int precedence(char op)

{

switch (op)

{

case '(': case ')': return 0; //우선 순위 낮음

case '+': case '-': return 1; //우선 순위 중간

case '*': case '/': return 2; //우선 순위 높음

}

return -1;

}


//중위 표기식을 후위 표기식으로 변환하는 함수

void infix2Postfix(FILE* fp = stdin)

{

char c, op;

double val;

ArrayStack st;


FILE* out;


out = fopen("test.txt", "w");


while ((c = getc(fp)) != '\n') //엔터가 입력되기 전까지

{

if ((c >= '0' && c <= '9')) //숫자로 시작되면

{

ungetc(c, fp); //문자를 돌려놓고

fscanf_s(fp, "%lf", &val); //double로 다시 읽는다

fprintf(out, "%4.1f", val);

}


else if (c == '(') // '(' 이면 스택에 삽입

{

st.push(c);

}


else if (c == ')') //')' 이면 '(' 가 나올때까지 연산자 출력

{

while (!st.isEmpty())

{

op = st.pop();

if (op == '(') break;

else fprintf(out, "%c", op);

}

}


else if (c == '+' || c == '-' || c == '*' || c == '/') //연산자이면

{

while (!st.isEmpty())

{

op = st.peek();

if (precedence(c) <= precedence(op)) //우선 순위 비교

{

fprintf(out, "%c", op);

st.pop();

}

else break;

}

st.push(c);

}

}

while (!st.isEmpty())

{

fprintf(out, "%c", st.pop());

}


fclose(out);

printf("\n");

}


//후위 표기식을 계산해주는 함수

double calcPostficExpr()

{

char c;

ArrayStack st;


FILE * fp = fopen("test.txt", "r");


if (fp == NULL)

{

return 1;

}


while ((c = getc(fp)) != '\n') //\n입력전까지

{

if (c == '+' || c == '-' || c == '*' || c == '/') //연산자 이면

{

double val2 = st.pop();

double val1 = st.pop();


switch (c)

{

case '+': st.push(val1 + val2); break;

case '-': st.push(val1 - val2); break;

case '*': st.push(val1 * val2); break;

case '/': st.push(val1 / val2); break;

}

}


else if (c >= '0' && c <= '9') //피연산자의 시작이면

{

ungetc(c, fp); //문자를 입력 버퍼에 돌려주고

double val;

fscanf_s(fp, "%lf", &val); //double 로 다시 읽음 (%lf는 double형의 실수)

st.push(val);

}

}


fclose(fp);

return (st.pop());

}


int main()

{


printf("수식 입력 (Infix) : ");

infix2Postfix();

double res = calcPostficExpr();


FILE* fp = fopen("test.txt", "w");


fprintf(fp, " = %f\n", res);


return 0;

}


<헤더 파일 코드>


#include <cstdio>

#include <cstdlib>


inline void error(const char* message)

{

printf("%s\n", message);

exit(0);

}


const int MAX_STACK_SIZE = 10; //스택 최대 크기

class ArrayStack

{

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");


}

};