2015年2月28日土曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の10章(プロセス間通信: お話は楽しい)、長いエクササイズ(p. 460)を解いてみる。

その他参考書籍

長いエクササイズ(p. 460)

コード(BBEdit, Emacs)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <signal.h>

#include <catch_signal.h>
#include <stopif.h>

int score = 0;

void end_game(int sig) {
  printf("\n最終得点: %i\n", score);
  exit(0);
}

void times_up(int sig) {
  printf("\n時間切れ!\n");
  raise(SIGINT);
}

int main() {
  catch_signal(SIGALRM, times_up);
  catch_signal(SIGINT, end_game);
  srandom (time (0));
  while (1) {
    int a = random() % 11;
    int b = random() % 11;
    alarm(5);
    printf("\n%iかける%iはいくつですか? ", a, b);
    char txt[4];
    fgets(txt, 4, stdin);
    char *end;
    int answer = strtol(txt, &end, 10);
    if (answer == a * b) score++;
    else printf("\n間違いです!得点: %i\n", score);
  }
}

入出力結果(Terminal)

$ make
clang ...
$ ./sample460

7かける4はいくつですか? 28

6かける4はいくつですか? 24

5かける5はいくつですか? 
時間切れ!

最終得点: 2
$ ./sample460

5かける2はいくつですか? 
時間切れ!

最終得点: 0
$ ./sample460

5かける7はいくつですか?   C-c C-c
最終得点: 0
$ 

0 コメント:

コメントを投稿