2013年5月8日水曜日

開発環境

プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第5章(ポインタと配列)、5.10(コマンド行の引数)、演習5-10を解いてみる。

その他参考書籍

演習 5-10.

コード

sample.c

#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>

#define MAXOP 100
#define NUMBER '0'
#define MAXVAL 100
#define BUFSIZE 100

int sp = 0;
double val[MAXVAL];
char buf[BUFSIZE];
int bufp = 0;

double atof(char []);
void push(double);
double pop(void);
int getch(void);
void ungetch(int);
int getop(char []);
void ungets(char s[]);

int main(int argc, char *argv[])
{
    double op2;
    char s[MAXOP];
    int c;
    float f;

    while  (--argc > 0) {
        ungets(" ");
        ungets(*++argv);
        switch (getop(s)) {
            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;
            default:
                printf("error: unkown command %s\n", s);
                argc = 0;
                break;
        }
    }
    printf("\t%.8g\n", pop());
    return 0;
}

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("error: stack empty\n");
        return 0.0;
    }
}

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

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

void ungets(char s[])
{
    int len = strlen(s);
    
    while (len > 0)
        ungetch(s[--len]);
}

int getop(char s[])
{
    int i, c;
    
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.')
        return c;
    i = 0;
    if (isdigit(c))
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.')
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;
}

入出力結果(Terminal)

$ ./a.out 2 3 4 + '*'
 14
$ ./a.out 1 2 - 4 5 + '*'
 -9
$ ./a.out 5 10 '*'
 50
$ ./a.out 1.5 5.1 '*'
 7.65
$

0 コメント:

コメントを投稿