C number guessing game with isdigit() verification

后端 未结 1 1545
时光取名叫无心
时光取名叫无心 2021-01-26 13:22

I\'m working on a challenge problem from my textbook where I\'m supposed to generate a random number between 1-10, let the user guess, and validate their response with isdigit()

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 14:15

    You can use the return value of scanf to determine whether the read was successful. So, there are two paths in your program, successful reading and failed reading:

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

    In the first case, you do whatever your program logic says. In the else case, you have to figure out "what was the problem", and "what to do about it":

    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');
    }
    

    0 讨论(0)
提交回复
热议问题