Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
逆ポーランド記法電卓っぽい何か
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 256
typedef struct stack {
int *stack;
int len;
} Stack;
void usage(char *name) {
printf("usage: %s input\n", name);
}
int push(Stack *s, int val) {
if (s->len >= MAX_LEN) {
return 0;
}
s->stack[s->len] = val;
s->len++;
return 1;
}
int pop(Stack *s) {
return s->stack[--s->len];
}
void dump(Stack *s) {
int i;
printf("[");
for (i = 0; i < s->len; i++) {
printf("%d,", s->stack[i]);
}
printf("]");
}
int add(Stack *s) {
int a = pop(s), b = pop(s);
return push(s, a + b);
}
int sub(Stack *s) {
int b = pop(s), a = pop(s);
return push(s, a - b);
}
void print(Stack *s) {
int a = pop(s);
printf("%c", a);
push(s, a);
}
int main(int argc, char *argv[]) {
FILE *fp;
char op;
int i;
char line[256];
char *tok;
int s[MAX_LEN];
Stack stack = { s, 0 };
if (argc < 2) {
usage(argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("cannot open: %s\n", argv[1]);
exit(1);
}
while (fgets(line, 256, fp) != NULL) {
tok = strtok(line, " ");
while (tok) {
if(sscanf(tok, "%d", &i)) {
push(&stack, i);
} else if (sscanf(tok, "%c", &op)) {
switch (op) {
case '+': {
if (!add(&stack)) {
printf("error: add\n");
exit(1);
}
break;
}
case '-': {
if (!sub(&stack)) {
printf("error: sub\n");
exit(1);
}
break;
}
case 'p': {
print(&stack);
break;
}
case 'd': {
dump(&stack);
break;
}
default:
break;
}
} else {
printf("invalid token: %s\n", tok);
exit(1);
}
tok = strtok(NULL, " ");
}
}
return 0;
}
42 31 + p 12 hog - 10 d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.