プログラミング言語 C
自由形式*1 入力変換を実行する関数 getint を作成せよ。
- /* getint.c */
- #include
- #include
/* 関数 isspace, isdigit に必要 */ - #define MAX 100
- int get_int(int *);
- int get_ch(void);
- void unget_ch(int);
- main()
- {
- int n, m = 0;
- int num[MAX];
- for (n = 0; n < MAX && get_int(&num[n]) != EOF; n++)
- ;
- while (m < n) {
- printf("%5d\n", num[m]);
- m++;
- }
- return 0;
- }
- int get_int(int *pn)
- {
- int c, sign; /* sign は正負記号 */
- while (isspace(c = get_ch()))
- ;
- /* 関数 isspace は c が space のとき真を返す */
- /* スペース (改行も) をスキップ */
- if (!isdigit(c) && c != '+' && c != '-') {
- unget_ch(c);
- return 0;
- }
- /* 関数 isdigit は c が '0'-'9' のとき真を返す */
- /* 入力が数字でないとき (!) 0 を返して終了 */
- sign = (c == '-') ? -1 : 1; /* 負の記号を記憶 */
- if (c == '+' || c == '-')
- c = get_ch();
- for (*pn = 0; isdigit(c); c = get_ch())
- *pn = 10 * *pn + (c - '0');
- *pn *= sign; /* *pn の正負を確定 */
- if (c != EOF)
- unget_ch(c);
- return c;
- /* ファイル終了時には EOF を、整数の入力時には正の値を返す */
- }
- char buf[MAX];
- int buf_pt = 0;
- int get_ch(void)
- {
- return (buf_pt > 0) ? buf[--buf_pt] : getchar();
- }
- void unget_ch(int c)
- {
- if (buf_pt >= MAX)
- printf("caution : buffer oversized\n");
- else
- buf[buf_pt++] = c;
- }
$./getint < random.txt
として実行してみると、最後に別のデータ?がくっついてくる . . . (数以外の文字列も うまく扱えないし)
あとで 直しても いっか。
(追記) 直しました。(05/10/19)
*1:スペースや改行でデータが区切られたファイル