Input validation of an Integer using atoi()

2020-01-27 08:49发布

#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. 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.

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 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?

Thanks.

2条回答
劫难
2楼-- · 2020-01-27 09:03

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). */
}
查看更多
\"骚年 ilove
3楼-- · 2020-01-27 09:06

There is the isdigit function that can help you check each character:

#include <ctype.h>

/* ... */

for (i=0; buffer[i]; i++) {
        if (!isdigit(buffer[i])) {
            printf("Bad\n");
            break;
        }
}   
查看更多
登录 后发表回答