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

问题描述 投票:0回答:1

当我的代码检查输入是否是整数或字符串时,它会进入输出“无效输入”和“猜测 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-statement while-loop integer break
1个回答
0
投票

当您尝试输入不是 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.");

}

© www.soinside.com 2019 - 2024. All rights reserved.