プログラミング演習II 課題1-2 区切り入力 by 아즈마

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

int stack[100]; /* スタック */
int stack_used; /* 使用しているスタックのエントリ数 */
int debug=1; /* debugモード時は1にする */

int emptystack(){ /* スタックが空かどうかの判定 */
    if(stack_used==0) return 1;
    return 0;
}

void initstack(){ /* スタックの初期化 */
    stack_used=0;
}

void push(int x){/* スタックにxを追加 */
    stack[stack_used]=x;
    stack_used++;
/* なんか入れる */
}

int pop(){/* スタックからデータを取得 */
    if(emptystack()){
        fprintf(stderr, "#### スタックが空になっています\n");
        return 0;
    }
    stack_used--;
    return stack[stack_used];
    
    /* なんか入れろ */
}

int top(){/* スタックからデータを取得 */
    return stack[stack_used-1];
}

void print_stack(){/* スタックの中身の表示 */
int i;
    printf("スタックの中身: ");
    for(i=0; i<stack_used; i++){
      printf("%d ",stack[i]);
     }
     printf("\n");
/* なんか入れろ */
}

int main(int argc){
int head, next;
char *input;

for(;;){
    printf("プロンプト> ");
    gets(input);



for(head=0; head<strlen(input); head=next+1){/* コマンドライン引数の未尾に至るまで */
    next=head;
    while(input[next]!=' '&&input[next]!='\0')next++;/* 空白 or 文字列の未尾を探す */

if(isdigit(input[head])){/* 数字の場合 */
    int num;
    sscanf(&input[head], "%d", &num);/* その数字を切り出して */
    if(debug) printf("<-%d(数値)\n", num);
    push(num);/* スタックに追加 */
}
else{/* 演算子の場合 */
int num1, num2, answer;
switch(input[head]){
case '+':
    if(debug) printf("<-'+'(演算子)\n");
    num1=pop();/* スタックからデータ取得 */
    num2=pop();/* スタックからデータ取得 */
    answer=num2+num1;/* 加算して */
    push(answer);/* スタックに追加 */
    break;
case '-':
    if(debug) printf("<-'-'(演算子)\n");
    num1=pop();
    num2=pop();
    answer=num2-num1;
    push(answer);
    break;
case '*':
    if(debug) printf("<-'*'(演算子)\n");
    num1=pop();
    num2=pop();
    answer=num2*num1;
    push(answer);
    break;
case '/':
    if(debug) printf("<-'/'(演算子)\n");
    num1=pop();
    num2=pop();
    answer=num2/num1;
    push(answer);
    break;
default:
    fprintf(stderr, "#### '%c'は未知の演算子です\n", input[head]);
    }
}
    if(debug) print_stack();
}
 }
  }

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://ldh21.egloos.com/tb/2466496 [도움말]

덧글

덧글 입력 영역