当检查变量是否为数字时,循环无限循环

时间:2018-05-08 12:12:10

标签: c

我对编程很陌生,所以回答这个问题可能很简单,但我无法找到它。当检查变量是否超过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);
}

1 个答案:

答案 0 :(得分:1)

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