C言語-トランスレータ(mbas to C) |
6. END, INPUT, PRINT の処理 (2)
各命令の動作にあったC言語プログラムを出力していく。その時、各命令の文法(書式、使い方)の詳細も決めていく。
[INPUT命令]
INPUT命令の書式を次の形式に決める。
書式
INPUT [文字定数 { , | ; }] 変数
[ ]内は省略可能を表し、{A|B}はAまたはBのどちらかを選択することを表す。
書式を構文図で表すと次のようになる。
○印は終端記号(末端記号)といい、他に種類のないものを表す。□印は非終端記号といい、その種類は別に定義される。
変換 | INPUT 文字定数, 変数 → | printf("文字定数"); gets(buff); 変数 = atof(buff); |
*A *B *C |
INPUT 文字定数; 変数 → | printf("文字定数"); printf(" ? "); gets(buff); 変数 = atof(buff); |
*A *D *B *C |
|
INPUT 変数 → | printf(" ? "); gets(buff); 変数 = atof(buff); |
*D *B *C |
プログラムは、関数として作成する。関数名は、mbtのINPUTなのでmbt_inputとする。引数も返却値もない。
関数mbt_input()では、変数名(A〜Z)を判定するため英字かどうかを判定する関数isalpha()を使うので、ctype.hをインクルードする。
#include <ctype.h>
int isalpha(int c);
文字cが英字(0x41〜0x5aまたは0x61〜0x7a)であるかを判定する。
返却値は、判定結果が正しければ0以外。正しくなければ0。
[main07.c] | |
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: |
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "gettoken.h" /* 関数のプロトタイプ宣言 */ @ void ptab(void); /* グローバル変数 */ int tab = 1; void main(int argc, char *argv[]) |
48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: |
/* 命令の判定 */ for(now = 0; now < last; ++now){ strcpy(gt_line, list[now]); /* 字句解析の準備 */ get_token(); /* トークンの取得 */ if(!strcmp("END", token)){ /* 命令の判定 */ ptab(); printf("printf(\"終了します\\n\");\n"); ptab(); printf("exit(1);\n"); }else if(!strcmp("INPUT", token)) mbt_input(); /* INPUT 命令の処理 */ else if(!strcmp("PRINT", token)) printf("PRINT 命令です\n"); |
80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 120: |
void mbt_input(void) { get_token(); /* 次のトークン取得 */ if(*token == '"'){ /* 文字定数あり */ ptab(); printf(A ); /* *Aの出力 */ get_token(); /* 次のトークン(区切り文字)取得 */ if(*token == ',') ; /* 何もしない */ else if(*token == ';'){ ptab(); printf("B "); /* *Dの出力 */ }else{ printf("INPUT 文法エラー \n"); exit(1); } get_token(); /* 次のトークン取得 */ }else{ /* 文字定数なし(変数のみ) */ ptab(); printf("B "); /* *Dの出力 */ } /* 変数かどうかのチェック */ if(!isalpha(*token) && strlen(token) >= 1){ printf("変数名は英字1文字のみです\n"); exit(1); } ptab(); printf("C "); /* *Bの出力 */ ptab(); printf("hensuu[%d] D ;\n", E ); /* *Cの出力 */ } void ptab(void) { <<省略>> } |
INPUT A INPUT Z PRINT Z PRINT A END |
D:\Data\src>cc main07.c gettoken.obj lld @link.i D:\Data\src>main07 reidai2.mb #include <stdio.h> #include <stdlib.h> void main(void) { double hensuu[26]; char buff[256]; printf(" ? "); gets(buff); hensuu[0] = atof(buff); printf(" ? "); gets(buff); hensuu[25] = atof(buff); PRINT 命令です PRINT 命令です printf("終了します\n"); exit(1); } |
Copyright © 2001 Hiroshi Masuda |