본문 바로가기

Native/C

reverse polish

//
// getop.cpp
//
#include <ctype.h>
#include "reverse_polish.h"

int getop(char s[])
{
    int i, c;

    while((s[0] = c = getchar()) == ' ' || c == '\t');
    s[1] = '\0';

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

    if(!isdigit(c) && c != '.')
        return c;

    i = 0;
    if(isdigit(c))
        while(isdigit(s[++i] = c = getchar()));

    if(c == '.')
        while(isdigit(s[++i] = c = getchar()));

    s[i] = '\0';    
    return NUMBER;

}

void test()
{
    printf("%c\n",NUMBER);
}

//
// push_pop.cpp
//
#include "reverse_polish.h"

#define MAXVAL 100

int sp=0;
double val[MAXVAL];

void push(double f)
{
    if(sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

double pop(void)
{
    if(sp > 0)
    {
        return val[--sp];
    }
    else
    {
        printf("errro: stack empty\n");
        return 0.0;
    }
}

//
// reverse_polish.cpp
//
#include "reverse_polish.h"

void main(void)
{
    int type;
    double op2;
    char s[MAXOP];

    while((type = getop(s))!=EOF)
    {
    //    printf("%c\n", type);

        switch(type)
        {
        case NUMBER:
            push(atof(s));
            break;
        case '+':
            push(pop() + pop());
            break;
        case '*':
            push(pop() + pop());
            break;
        case '-':
            op2 = pop();
            push(pop() - op2);
            break;
        case '/':
            op2 = pop();
            if(op2 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor\n");
            break;
        case '\n':
            printf("\t%.8g\n",pop());
            break;
        default:
            printf("error:unknown command %s\n", s);
            break;
        }
    }
}


//
// reverse_polish.h
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAXOP 100
#define NUMBER '0'

void push(double);
double pop(void);
int getop(char *);
void test();
int getch(void);
void ungetch(int);

//
// getch.cpp
//
#include "reverse_polish.h"

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
    return (bufp >0)?buf[--bufp]:getchar();
}

void ungetch(int c)
{
    if(bufp >= BUFSIZE)
        printf("ungetch : too many back on input : ");
    else
        buf[bufp++] = c;
}

'Native > C' 카테고리의 다른 글

계산기  (0) 2013.10.02
중위 표기법 -> 후위표기법으로 변경후 계산  (0) 2013.10.02
mystrstr (해당 문자열이 몇개 있는지 확인하기) bugfix 050419  (0) 2013.10.02
예제 3-3 진행중  (0) 2013.10.02
예제 2-6 UpVer  (0) 2013.10.02