仅用于正整数的用户验证

时间:2015-10-08 15:05:12

标签: c

我正在编写一个只接受大于0的正整数的程序,而不是其他东西。问题是当用户输入十进制数时,如何验证如果权重是十进制数,我再次询问用户。

printf("Please enter your weight in pounds: ");
scanf("%d", &weight);

while(weight <= 0)
{
    printf("Invalid weight! Please enter a positive number: ");
    scanf("%d", &weight);
}
printf("Your weight is %d\n",weight);

2 个答案:

答案 0 :(得分:0)

使用fgets将数据输入字符串缓冲区,检查字符串是否只包含数字,然后使用sscanfatoi将字符串转换为数字。最后检查数字是否大于0.

答案 1 :(得分:0)

这是一个解决方案(未经测试)

int weight = 0, c;
printf("Please enter your weight in pounds: ");

for(;;) { /* Infinite loop */
  if(((c = scanf("%d", &weight)) == 1 || c == EOF) && weight > 0 && ((c = getchar()) == EOF || c == '\n'))
  /* If the user enters a valid integer and it is a positive number and if the next character is either EOF or '\n' */
    break; /* Get out of the loop */

  /* If the execution reaches here, something invalid was entered */

  printf("Invalid weight! Please enter a positive number: ");
  while((c = getchar()) != EOF && c != '\n'); /* Clear the stdin */
}

if(c != EOF)
  printf("Your weight is %d\n",weight);