cstrtol

How do u make strtol convert 0


void isInt(char *string)
{
    if (strlen(string) > 2)
        printf("Invalid")

    if (!strtol(string, &endptr, 10))
        printf("Invalid")

    printf("Valid")
}

i have this code which checks if a series of 1 or 2 characters contain only integers for example 12, 1, 10 would be valid but 6g, ii would not be valid. The problem i have is that if the input string contains a 0 then it returns invalid for example 0 or 10 should be valid but are not. How would i let 0 be valid? or is there just an overall easier way to do this?


Solution

  • Would you please try:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void isInt(char *string)
    {
        char *endptr;
        long val;
    
        if (strlen(string) > 2) {
            printf("String too long: %s\n", string);
            return;
        }
        val = strtol(string, &endptr, 10);
        if (*endptr != '\0') {
            printf("Invalid string: %s \n", string);
            return;
        } else {
            printf("Valid: %s\n", string);
        }
    }
    
    int main()
    {
        isInt("2");
        isInt("10");
        isInt("0");
        isInt("6g");
    
        return 0;
    }
    

    Output:

    Valid: 2
    Valid: 10
    Valid: 0
    Invalid string: 6g