C猜谜游戏使用while循环限制用户猜测,用isdigit进行验证

C guessing game using while loops to limit user guesses and isdigit for verification

任务:

我面临的问题:我是编程新手,所以我还没有太多经验。这是我第一次尝试理解 is digit 函数,我觉得有一种更有效的方法可以解决这个问题。

    #include <stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    int main()
    {
        int iRandomNum = 5;         //setting up a number as a placeholder until Code works
        char guess;                 //char being used as I beleive it needs to be char for isdigit to function
        int guessCount = 0;         //
        int guessLimit = 3;
        int outOfGuess = 0;
    
        srand(1-10);
        //iRandomNum = (rand()%20)+1;
        while (guess != iRandomNum && guessCount != 3 && outOfGuess == 0){  //Intended to break out of loop once any variable is satisfied
            if(guessCount< guessLimit){
                    printf("\n%d", iRandomNum);
                    printf("\nYou have %d guesses left", guessLimit- guessCount);   //extra user info
                    printf("\nGuess the number between 1 - 10: ");
                    scanf(" %s", &guess);
    
                if (isdigit(guess)==0)
                    {
                        printf("\nEnter a digit!");
                        guessCount++;               //supposed to limit user to 3 chances
                    }else
                    {         //need help solving this
                        printf("\nYou entered %d\n", guess - 48); //Using for testing
                        guess = guess - 48;
                        if (guess == iRandomNum)       //I dont think functions as char and int are different data types
                        {
                            printf("\nYou've Won");
                            break;
                        }else{
                            printf("\nWrong guess");
                            guessCount++;
                            }
                    }
    
            }else        //Once user runs out of guesses while loop should break an then display following data
                {
                    printf("Second else");
                    guessCount++;
                    //outOfGuess = 1;
                }
            }
    
        if (outOfGuess == 1){
            printf("\nOut of guesses!");
        }
        else{
            printf("\nCongratulations!");
        }
        return 0;
    
    }

评论中未提及的问题:guess 在被赋值之前用于 while 条件 - 这是一个错误。

关于主要问题:

  • 为了让用户输入多于 1 个字符(即对于两位数最多两个字符),您可以使用足够大小的字符数组。当然,当使用“Isdigit” 检查 时,你必须考虑第二个字符。所以e。 G。替换

                       scanf(" %s", &guess);
       
                   if (isdigit(guess)==0)
    

                char s[2+1];    // +1 for string-terminating null character
                if (scanf(" %2s", s) < 1 || !isdigit(s[0]) || s[1] && !isdigit(s[1]))
    
  • 为了将数组中的字符串转换为整数,可以简单地使用atoi:

                    guess = atoi(s);