Home > Mobile >  How do u make strtol convert 0
How do u make strtol convert 0

Time:03-29

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?

CodePudding user response:

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 

CodePudding user response:

If you are not bound to strtol(), then isdigit() gives you a simpler solution:

void isInt(const char *string) {
    if (isdigit(string[0]) && isdigit(string[1])) {
        printf("Valid");
    } else {
        printf("Invalid");
    }
}
  • Related