[英]Input validation of an Integer using atoi()
#include "stdafx.h"
#include <stdlib.h>
void main()
{
char buffer[20];
int num;
printf("Please enter a number\n");
fgets(buffer, 20, stdin);
num = atoi(buffer);
if(num == '\0')
{
printf("Error Message!");
}
else
{
printf("\n\nThe number entered is %d", num);
}
getchar();
}
The above code accepts a number in the form of a string and converts it to integer using atoi. 上面的代码接受字符串形式的数字,并使用atoi将其转换为整数。 If the user inputs a decimal number, only the bit before the decimal is accepted. 如果用户输入十进制数,则仅接受十进制前的位。 Moreover, if the user enters a letter, it returns 0. 此外,如果用户输入字母,则返回0。
Now, I have two queries: 现在,我有两个查询:
i) I want the program to detect if the user entered a number with decimal point and output an error message. i)我希望程序检测用户是否输入了带小数点的数字并输出错误消息。 I don't want it to take the part before the decimal point. 我不希望它在小数点前出现。 I want it to recognize that the input is invalid. 我希望它识别出输入无效。
ii) If atoi returns 0 in case there are letters, how can I validate it since the user can enter the number 0 as well? ii)如果在有字母的情况下atoi返回0,那么由于用户也可以输入数字0,该如何验证?
Thanks. 谢谢。
atoi
is not suitable for error checking. atoi
不适合进行错误检查。 Use strtol
or strtoul
instead. 请改用strtol
或strtoul
。
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
long int result;
char *pend;
errno = 0;
result = strtol (buffer, &pend, 10);
if (result == LONG_MIN && errno != 0)
{
/* Underflow. */
}
if (result == LONG_MAX && errno != 0)
{
/* Overflow. */
}
if (*pend != '\0')
{
/* Integer followed by some stuff (floating-point number for instance). */
}
There is the isdigit
function that can help you check each character: 有isdigit
函数可以帮助您检查每个字符:
#include <ctype.h>
/* ... */
for (i=0; buffer[i]; i++) {
if (!isdigit(buffer[i])) {
printf("Bad\n");
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.