更高/更低的博弈 - 如何在 while 循环中检查输入是否为整数

higher/lower game - how do I check if an input is an integer or not in a while loop

提问人:kakarot 22 提问时间:11/6/2023 更新时间:11/6/2023 访问量:67

问:

当我的代码检查输入是整数还是字符串时,它会进入输出“无效输入”和“猜测 0-9 之间的数字”的无限循环,而不会给用户输入新内容的机会。

下面的代码是我所拥有的

// Created on: Oct 2023    
// This program allows the user to guess a number between 0-9  
#include <stdlib.h>  
#include <stdio.h>  
#include <time.h>  

int main() {  
    // this function allows the user to guess a number  
    // and the program decides if the user is correct  

    unsigned int seed = time(NULL);  
    int randomNumber = rand_r(&seed) % 9;  
    int num = 0;  
    int scanerrorcode = 0;  
    
    while (1)  
    {  
        printf("\nGuess a number between 0-9: ");  
        scanf("%d", &num);
        if (num < 0 || num > 9) {
            printf("\n%d is not between 0-9", num);
        } else if (num == randomNumber) {
            printf("\nYou guessed correctly!");
            break;
        } else if (num > randomNumber) {  
            printf("\nYou guessed too high!");  
        } else if (num < randomNumber) {  
            printf("\nYou guessed too low!");  
        } else {  
            printf("\nError, %d is not a number", num);  
        }  
    }  

    printf("\nDone.");  
}

我正在寻找一种方法来制作这个游戏,只使用 while 循环和 break 语句。代码应不断要求用户输入,直到猜到随机数

c if 语句 while-loop 整数 中断

评论

0赞 greg spears 11/6/2023
对不起,我不能重复你的错误。代码对我有用。具体来说,它会不断循环并要求我输入一个号码,直到我输入正确的号码。当我输入正确的数字时,它会打印“完成”并退出。
0赞 Fe2O3 11/6/2023
"检查输入是整数还是字符串“ 不,它不是。 当调皮的用户进入时不满意,所以它把它留在输入缓冲区中,只是为了一次又一次地找到它。了解如何在一次操作中使用和清空缓冲区,并验证用户的输入是否是程序正常工作所需的内容。远离 .它不适合初学者......scanf()"foobar"fgets()strtol()scanf()

答:

-1赞 Matthew Sexton 11/6/2023 #1

当您尝试输入一个不是 0 到 9 的值(因此像 a、b、c 等字符)时,您会得到垃圾值,您需要将其作为 char 获取并通过应用偏移量将其转换为 asci ii 值。

int main() {  
unsigned int seed = time(NULL);
int randomNumber = rand_r(&seed) % 9;
int scanerrorcode = 0;

while (1)
{
    int num = 0; //need to reset ever time we loop
    char ch;
    printf("\nGuess a number between 0-9: ");  
    scanf(" %c", &ch);  

    //ascii 2 char for 0 - 9 is 48 - 57! https://www.ascii-code.com/
    printf("The ASCII value of %c is %d \n", ch, ch);

    // To make a digit
    num = num * 10 + (ch - 48);

    //Hey look it's valid!
    if (ch >= 48 && ch <= 57) {
        printf("\n%d is valid and between 0-9", num);
    }

    //not valid!
    if (ch> 57 || ch < 48){
        printf("\n%d is NOT between 0-9!", num);
    } else if (num == randomNumber) {
        printf("\nYou guessed correctly!");
        break;
    } else if (num > randomNumber) {
        printf("\nYou guessed too high!");
    } else if (num < randomNumber) {
        printf("\nYou guessed too low!");
    } else {
        printf("\nError, %d is not a number", num);
    }
}  

printf("\nDone.");

}

评论

1赞 Fe2O3 11/6/2023
“如果你不鼓励在答案中使用幻数,那就更好了。有什么问题,而不是,同样......'0'48'9'
0赞 Matthew Sexton 11/6/2023
我假设这是一个针对新生的项目。他会没事的。
0赞 NoDakker 11/6/2023 #2

我尝试了您的代码,确实,如果输入某些字符作为数据,程序确实会陷入无限循环。在查看代码时,您似乎是时候熟悉传统的字符和字符串功能了(例如,检查字符是否为数字、将字符串转换为整数等)。

考虑到这一点,以下是代码的重构版本。

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

int main() {
    // This function allows the user to guess a number
    // and the program decides if the user is correct

    int i;
    unsigned int seed = time(NULL);
    int randomNumber = rand_r(&seed) % 9;
    char num[5];

    while (1)
    {
        printf("Guess a number between 0-9: ");
        i = scanf("%s", num);                                   /* Input user entry into a character array                          */

        for (i = 0; i < strlen(num); i++)                       /* Ensure no non-digits are entered in the for loop test            */
        {
            if ((isdigit(num[i]) == 0))
                break;
        }

        if ((isdigit(num[i]) == 0) && (i < strlen(num))) {
            printf("Error, %s is not a number\n", num);       /* Move non-digit test as the first test                            */
            continue;
        }

        i = atoi(num);                                          /* Use conventional string function to convert string to an integer */

        if ((i < 0) || (i > 9)) {
            printf("%d is not between 0 - 9\n", i);
        } else if (i == randomNumber) {
            printf("You guessed correctly!\n");
            break;
        } else if (i > randomNumber) {
            printf("You guessed too high!\n");
        } else {
            printf("You guessed too low!\n");
        }
    }

    printf("Done.\n");

    return 0;
}

添加了评论,但这里有一些关键点。

  • 添加了“string.h”和“ctype.h”包含文件以利用标准字符操作。
  • 在“scanf”函数中,使用字符数组代替整数进行数据输入(请注意,没有与号)。
  • 然后验证字符数组条目,确保仅输入数字,输入的值在猜测范围内,然后猜测相对于随机数的位置。

接下来是在终端进行试运行。

craig@Vera:~/C_Programs/Console/Guess/bin/Release$ ./Guess 
Guess a number between 0-9: huh
Error, huh is not a number
Guess a number between 0-9: 11
11 is not between 0 - 9
Guess a number between 0-9: 5
You guessed too high!
Guess a number between 0-9: 2
You guessed too low!
Guess a number between 0-9: 3
You guessed correctly!
Done.

从中得到的启示可能是参考一些关于字符串和字符函数用法的优秀教程文献。