開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第5章(ポインタと配列)、5.12(複雑な宣言)、演習5-19を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 5-19.
コード
sample.c
#include <stdio.h> #include <string.h> #include <ctype.h> #define MAXTOKEN 100 enum {NAME, PARENS, BRACKETS}; enum {NO, YES}; int gettoken(void); int getnexttoken(void); void error(char *); int tokentype; char token[MAXTOKEN]; char name[MAXTOKEN]; char out[1000]; int pretoken; int main() { int type; char temp[MAXTOKEN]; while (gettoken() != EOF) { strcpy(out, token); while ((type = gettoken()) != '\n') { if (type == PARENS || type == BRACKETS) { strcat(out, token); } else if (type == '*') { /* *の次が(丸|角)括弧じゃなければ、丸括弧で優先順位を付ける必要はない。*/ if ((type = getnexttoken()) == PARENS || type == BRACKETS) { sprintf(temp, "(*%s)", out); } else { sprintf(temp, "*%s", out); } strcpy(out, temp); } else if (type == NAME) { sprintf(temp, "%s %s", token, out); strcpy(out, temp); } else { printf("invalid input at %s\n", token); } } printf("%s\n", out); } return 0; } int gettoken(void) { int c, getch(void); void ungetch(int); char *p = token; if (pretoken == YES) { pretoken = NO; return tokentype; } while ((c = getch()) == ' ' || c == '\t') ; if (c == '(') { if ((c = getch()) == ')') { strcpy(token, "()"); return tokentype = PARENS; } else { ungetch(c); return tokentype = '('; } } else if (c == '[') { for (*p++ = c; (*p++ = getch()) != ']'; ) ; *p = '\0'; return tokentype = BRACKETS; } else if (isalpha(c)) { for (*p++ = c; isalnum(c = getch()); ) { *p++ = c; } *p = '\0'; ungetch(c); return tokentype = NAME; } else { return tokentype = c; } } int getnexttoken(void) { int type; type = gettoken(); pretoken = YES; return type; } void error(char *s) { printf("%s", s); pretoken = YES; } #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 characters\n"); } else { buf[bufp++] = c; } }
入出力結果(Terminal)
$ ./a.out c * char char *c $
0 コメント:
コメントを投稿