C 仅对正整数进行用户验证

C 仅对正整数进行用户验证,c,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"

我正在编写一个程序,它只接受大于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);
使用fgets获取输入字符串缓冲区的数据,检查字符串是否仅包含数字,然后使用sscanf或atoi将字符串转换为数字。最后检查数字是否大于0。

这是算法

->take an array of characters
->read the number in array
->the first character should be a '+' or a '0 - 9'
->the remaining characters should be '0 - 9'
这是一个正数

如果您想将其转换为数字,请使用标准库中的atoi函数

这是一个未经测试的解决方案:

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