Advertisement
dc1394

Untitled

Dec 24th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. // 2019/12/22(日)
  2. // 2019/12/25(水) L8改変
  3.  
  4. #include <errno.h>
  5. #include <stdbool.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <limits.h>
  10. #include <time.h>
  11.  
  12. #define MAXBUF 3
  13.  
  14. bool geti(int * n);
  15. bool my_getline(char * line, size_t size);
  16.  
  17. int main()
  18. {
  19.     srand((unsigned)time(0UL));
  20.     int answer = rand() % 10;
  21.     bool isAtari = false;
  22.  
  23.     printf("***数当てゲーム(Lv1)***\n");
  24.     printf("回答のチャンスは4回まで\n");
  25.     for (int i = 1; i <= 4; i++) {
  26.         int num;
  27.         bool isSuccess;
  28.  
  29.         do {
  30.             printf("1桁の数を入力:");
  31.             isSuccess = geti(&num);
  32.         } while (!isSuccess);
  33.  
  34.         if (num == answer) {
  35.             printf("当たり!(%d回目)\n", i);
  36.             isAtari = true;
  37.             break;
  38.         }
  39.  
  40.         printf("残念、はずれです(入力:%d、%d回目)\n", num, i);
  41.  
  42.         if (num < answer) {
  43.             printf("もっと大きな数です\n\n");
  44.         }
  45.         else {
  46.             printf("もっと小さな数です\n\n");
  47.         }
  48.     }
  49.  
  50.     if (!isAtari) {
  51.         printf("正解は%dでした\n", answer);
  52.     }
  53.  
  54.     return 0;
  55. }
  56.  
  57. bool geti(int * n)
  58. {
  59.     char line[MAXBUF];
  60.     char * endp;
  61.     long val;
  62.  
  63.     if (!my_getline(line, sizeof(line))) {
  64.         return false;
  65.     }
  66.  
  67.     errno = 0;
  68.     val = strtol(line, &endp, 0);
  69.  
  70.     if (val == 0 && errno != 0) {
  71.         return false;
  72.     }
  73.     if (endp == line || *endp != '\0') {
  74.         return false;
  75.     }
  76.  
  77.     *n = val;
  78.     return true;
  79. }
  80.  
  81. bool my_getline(char * line, size_t size)
  82. {
  83.     char * s;
  84.     int c;
  85.  
  86.     if (fgets(line, (int)size, stdin) == NULL) {
  87.         return false;
  88.     }
  89.  
  90.     s = strchr(line, '\n');
  91.  
  92.     if (s == line) {
  93.         return false;
  94.     }
  95.     if (s == NULL) {
  96.         if (strlen(line) + 1 == size) {
  97.             while ((c = getchar()) != EOF && c != '\n') {
  98.             }
  99.             return false;
  100.         }
  101.     }
  102.  
  103.     *s = '\0';
  104.     return true;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement