Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading