0

私は、1 から 10 の間の乱数を生成し、ユーザーに推測させ、isdigit() で応答を検証することになっている教科書のチャレンジ問題に取り組んでいます。私は(ほとんど)以下のコードでプログラムを動作させました。

私が遭遇した主な問題は、 isdigit() を使用するには入力を char として保存する必要があり、比較の前に変換する必要があったため、数値の ASCII コードではなく実際の数値が比較されました。

私の質問は、この変換は 0 ~ 9 の数字に対してのみ機能するため、コードを変更して、生成された数字が 10 である場合にユーザーが 10 を正しく推測できるようにするにはどうすればよいですか? または、ゲームの範囲を 1 ~ 100 にしたい場合はどうすればよいでしょうか。0 ~ 9 より大きい範囲を使用している場合、isdigit() で入力を検証できませんか? ユーザー入力を確認するより良い方法は何ですか?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

int main(void) {

  char buffer[10];
  char cGuess;
  char iNum;
  srand(time(NULL));

  iNum = (rand() % 10) + 1;

  printf("%d\n", iNum);
  printf("Please enter your guess: ");
  fgets(buffer, sizeof(buffer), stdin);
  sscanf(buffer, "%c", &cGuess);

  if (isdigit(cGuess)) 
  {
    cGuess = cGuess - '0';

    if (cGuess == iNum)
      printf("You guessed correctly!");
    else
    {
      if (cGuess > 0 && cGuess < 11)
        printf("You guessed wrong.");
      else
        printf("You did not enter a valid number.");
    }
  }
  else
    printf("You did not enter a correct number.");




return(0);
}
4

1 に答える 1

0

の戻り値を使用してscanf、読み取りが成功したかどうかを判断できます。したがって、プログラムには、読み取りの成功と読み取りの失敗の 2 つのパスがあります。

int guess;
if (scanf("%d", &guess) == 1)
{
    /* guess is read */
}
else
{
    /* guess is not read */
}

最初のケースでは、プログラム ロジックが言うことは何でもします。そのelse場合、「何が問題だったのか」と「それに対して何をすべきか」を把握する必要があります。

int guess;
if (scanf("%d", &guess) == 1)
{
    /* guess is read */
}
else
{
    if (feof(stdin) || ferror(stdin))
    {
        fprintf(stderr, "Unexpected end of input or I/O error\n");
        return EXIT_FAILURE;
    }
    /* if not file error, then the input wasn't a number */
    /* let's skip the current line. */
    while (!feof(stdin) && fgetc(stdin) != '\n');
}
于 2013-03-18T11:19:15.967 に答える