gpt4 book ai didi

c - While 循环在检查变量是否为数字时无限循环

转载 作者:行者123 更新时间:2023-11-30 14:48:42 24 4
gpt4 key购买 nike

我对编程很陌生,所以这个问题的答案可能很简单,但我找不到它。当检查变量是超过 1000 还是低于 1 时,程序可以工作,但每当我输入一个字母时,程序就会无限循环。无论如何,这是代码,感谢您的帮助:

printf("Player 1 enter A number between 1 and 1000: ");
scanf("%d", &num);

while(num<1 || num>1000 || !isdigit(num)){
printf("please enter different number: ");
scanf("%d", &num);
}

最佳答案

scanf 是读取用户输入的糟糕选择。

您可能想要这个:

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

// Get a number from the user
// number: pointer to the number
// return value: 1 if the user has typed a number
// 0 if the user ha not typed a number

int GetNumber(int *number)
{
char inputbuffer[20];

fgets(inputbuffer, sizeof inputbuffer, stdin); // read raw line from user
if (!isdigit(inputbuffer[0])) // if first char isn't a digit
return 0; // it's not a number, return 0

*number = strtol(inputbuffer, NULL, 10); // convert to number
return 1;
}


int main()
{
int num;

printf("Player 1 enter A number between 1 and 1000: ");

while (!GetNumber(&num) || num < 1 || num > 1000) {
printf("please enter different number: ");
}

printf("number = %d\n", num);

return 0;
}

GetNumber 的替代版本:

int GetNumber(int *number)
{
char inputbuffer[20];

fgets(inputbuffer, sizeof inputbuffer, stdin);

char *endptr;
*number = strtol(inputbuffer, &endptr, 10);
if (*endptr != '\n') // if user input ends with somethign else than
return 0; // \n it's not a number (e.g: "123a")

return 1;
}

关于c - While 循环在检查变量是否为数字时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com