Input validation of an Integer using atoi()

后端 未结 2 1554
鱼传尺愫
鱼传尺愫 2020-11-30 15:33
#include \"stdafx.h\"
#include 

void main()
{
    char buffer[20];
    int num;

    printf(\"Please enter a number\\n\");
    fgets(buffer, 20, std         


        
相关标签:
2条回答
  • 2020-11-30 16:24

    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). */
    }
    
    0 讨论(0)
  • 2020-11-30 16:37

    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;
            }
    }   
    
    0 讨论(0)
提交回复
热议问题