fork download
  1. #pragma warning(disable:4996)
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. typedef struct {
  8. const char *question;
  9. const char *choices[3];
  10. int correct; // 1〜3
  11. int points;
  12. } Quiz;
  13.  
  14. static int read_answer_1to3(void) {
  15. char buf[64];
  16.  
  17. while (1) {
  18. printf("回答(1〜3)> ");
  19. if (fgets(buf, sizeof(buf), stdin) == NULL) {
  20. return -1; // 入力終了など
  21. }
  22.  
  23. // 改行除去
  24. buf[strcspn(buf, "\r\n")] = '\0';
  25.  
  26. char *end = NULL;
  27. long v = strtol(buf, &end, 10);
  28.  
  29. // 数字以外が混じる/空/範囲外はやり直し
  30. if (end == buf || *end != '\0') {
  31. puts("数字だけで入力してください。");
  32. continue;
  33. }
  34. if (v < 1 || v > 3) {
  35. puts("1〜3の範囲で入力してください。");
  36. continue;
  37. }
  38. return (int)v;
  39. }
  40. }
  41.  
  42. int main(void) {
  43. Quiz quizzes[6] = {
  44. {
  45. "かな文字で,物語「源氏物語」を書いた。",
  46. {"1. 紫式部", "2. 天草四郎", "3. ヘレン・ケラー"},
  47. 1, 20
  48. },
  49. {
  50. "随筆「枕草子」を書いた。",
  51. {"1. エジソン", "2. 小野小町", "3. 清少納言"},
  52. 3, 15
  53. },
  54. {
  55. "全国各地を実測し,日本地図の作成に努めた。",
  56. {"1. 徳川家光", "2. 伊能忠敬", "3. 吉田松陰"},
  57. 2, 10
  58. },
  59. {
  60. "日本最初の内閣総理大臣。",
  61. {"1. 田中正造", "2. 小村寿太郎", "3. 伊藤博文"},
  62. 3, 15
  63. },
  64. {
  65. "「学問のすすめ」を書いた人物。",
  66. {"1. 福沢諭吉", "2. 樋口一葉", "3. 新渡戸稲造"},
  67. 1, 20
  68. },
  69. {
  70. "細菌学者(医者)として,黄熱病の解明に努めた。",
  71. {"1. 山本五十六", "2. 吉田茂", "3. 野口英世"},
  72. 3, 20
  73. }
  74. };
  75.  
  76. int total = 0;
  77. const int n = (int)(sizeof(quizzes) / sizeof(quizzes[0]));
  78.  
  79. puts("--------クイズを答えてください。--------");
  80.  
  81. for (int i = 0; i < n; i++) {
  82. puts("");
  83. printf("第%d問(配点 %d点)\n", i + 1, quizzes[i].points);
  84. puts(quizzes[i].question);
  85. puts(quizzes[i].choices[0]);
  86. puts(quizzes[i].choices[1]);
  87. puts(quizzes[i].choices[2]);
  88.  
  89. int ans = read_answer_1to3();
  90. if (ans == -1) {
  91. puts("\n入力が終了しました。");
  92. break;
  93. }
  94.  
  95. if (ans == quizzes[i].correct) {
  96. puts("正解です。");
  97. total += quizzes[i].points;
  98. } else {
  99. printf("不正解です。正解は%dです。\n", quizzes[i].correct);
  100. }
  101. }
  102.  
  103. puts("");
  104. printf("あなたの得点は %d 点です。\n", total);
  105.  
  106. return 0;
  107. }
  108.  
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
--------クイズを答えてください。--------

第1問(配点 20点)
かな文字で,物語「源氏物語」を書いた。
1. 紫式部
2. 天草四郎
3. ヘレン・ケラー
回答(1〜3)> 
入力が終了しました。

あなたの得点は 0 点です。