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

查看:224
本文介绍了使用的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();
}

以上code接受一个字符串形式的数字,并将其转换使用的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 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.

二)如果与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 != '\0') 
{
    /* Integer followed by some stuff (floating-point number for instance). */
}

这篇关于使用的atoi整数的输入验证()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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