问题描述
#include "stdafx.h"
#include <stdlib.h>
void main()
{
char buffer[20];
int num;
printf("Please enter a number
");
fgets(buffer, 20, stdin);
num = atoi(buffer);
if(num == ' ')
{
printf("Error Message!");
}
else
{
printf("
The number entered is %d", num);
}
getchar();
}
上面的代码接受一个字符串形式的数字,并使用atoi将其转换为整数.如果用户输入一个十进制数,则只接受小数前的一位.而且,如果用户输入一个字母,则返回0.
The above code accepts a number in the form of a string and converts it to integer using 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.
现在,我有两个查询:
i) 我希望程序检测用户是否输入了带小数点的数字并输出错误消息.我不希望它占用小数点前的部分.我想让它识别输入无效.
i) I want the program to detect if the user entered a number with decimal point and output an error message. I don't want it to take the part before the decimal point. I want it to recognize that the input is invalid.
ii) 如果 atoi 返回 0 以防有字母,我如何验证它,因为用户也可以输入数字 0?
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?
谢谢.
推荐答案
atoi
不适合错误检查.使用 strtol
或 strtoul
代替.
atoi
is not suitable for error checking. Use strtol
or strtoul
instead.
#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 != ' ')
{
/* Integer followed by some stuff (floating-point number for instance). */
}
这篇关于使用 atoi() 对整数进行输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!