使用 atoi() 对整数进行输入验证 [英] Input validation of an Integer using atoi()

查看:38
本文介绍了使用 atoi() 对整数进行输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 不适合错误检查.使用 strtolstrtoul 代替.

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() 对整数进行输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆