[Solved] Is there any way to compare 2 strings with different lengths using strcmp in C [closed]


@AndrewHenle commented:

If you want to compare numbers with different numbers of digits and not strings, you need to convert the strings to actual numbers.

As it is clear from your comments that you want to compare the numeric value that is contained in the strings, you need to do just that — convert the strings to actual numbers.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
    char st[100] = "24";
    char st1[100]= "4";

    long val, val1;
    char * endptr;

    errno = 0;
    val = strtol( st, &endptr, 10 );
    if ( errno == ERANGE || *endptr != '\0' )
    {
        // error parsing st -- not a number, or additional characters
        return EXIT_FAILURE;
    }

    val1 = strtol( st1, &endptr, 10 );
    if ( errno == ERANGE || *endptr != '\0' )
    {
        // error parsing st1 -- not a number, or additional characters
        return EXIT_FAILURE;
    }

    printf("%ld", val - val1);
    return EXIT_SUCCESS;
}

You could just use atoi, especially if you can guarantee the fields to contain numbers and nothing but numbers within the proper value range (due to having parsed them from the date input you are apparently processing), but I preferred to showcase the more robust, error-checking version.

0

solved Is there any way to compare 2 strings with different lengths using strcmp in C [closed]