[英]User validation for positive integer only
I'm writing a program that only accepts a positive int greater than 0 and nothing else. 我正在编写一个程序,该程序只接受大于0的正整数,而没有别的。 The problem is when the user enters a decimal number, how do I validate that if weight is a decimal number I ask the user again. 问题是当用户输入十进制数字时,如何验证重量是否为十进制数字,请再次询问用户。
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);
Use fgets
to get the data entered into a string buffer, check that the string only contains numbers, and only then use sscanf
or atoi
to convert the string to a number. 使用fgets
获取输入到字符串缓冲区的数据,检查字符串是否仅包含数字,然后再使用sscanf
或atoi
将字符串转换为数字。 Finally check that the number is larger than 0. 最后检查数字是否大于0。
this is the algorithm 这是算法
->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'
that's it is a positive number 那是一个正数
if you want to convert it into number use atoi function in standard library 如果要将其转换为数字,请使用标准库中的atoi函数
http://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm http://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm
This is a solution (untested) : 这是一个解决方案(未试用) :
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.