プログラミング言語 C

先に 進む前に、3月27日の 日記を 訂正。(p117-118)


/* 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 ", num[m]);
m++;
}
putchar('\n');

return 0;
}

int get_int(int *pn)
{
/* get_int : 入力から 整数を取り出して *pn に 格納 */
/* ファイル終了時には EOF を、数の入力時には 正の値を 返す */

int c, sign; /* sign は 正負記号 */

while (isspace(c = get_ch()));
;
/* 関数 isspace は c が space のとき 真を返す */
/* スペースは スキップ */

if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
unget_ch(c);
return 0;
}
/* 関数 isdigit は c が 数のとき 真を返す */
/* 文字が 数でない (!) ときは 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;

if (c != EOF)
unget_ch(c);

return c;
}

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)
puts("caution: buffer oversized\n");
else
buf[buf_pt++] = c;
}

コンパイルして、random.txt で 確認。

$cc -c getint.c
$cc -o getint getint.o
$./getint < random.txt
(追記) ちょっと 訂正。