hello i got a problem with comparing two char* variables that contains numbers for example
char1 = "999999" and char2="11111111"
when i am using the strcmp function it will return that char1 variable is greater than char2
even tho its wrong.
(i know that i can compare with using the atoi function till 9 chars inside the string but i need to use 10 so it cuts this possibility).
A slightly more cumbersome way, that avoids atoi and friends, is to prefix the shorter of the two strings with zeroes. Or, assuming there are no prefixing zeroes, simply first comparing the length (since shorter strings must have a lower value), then running a lexiographic comparison:
int numerical_strcmp(const char* a, const char* b) {
return (strlen(a) != strlen(b)) ? ((strlen(a) > strlen(b)) ? 1 : -1) : strcmp(a, b);
}
Oh, and this requires the strings to contain non-negative numbers.
Actually, it's right. It's doing a string comparison of the contents of the strings, not a numeric one.
As a quick and dirty hack, assuming that you've already validated that the strings contain positive integers, you could do the following:
if (strlen(char2) > strlen(char1)) {
// char2 > char1
} else if (strlen(char2) == strlen(char1)) {
cmp = strcmp(char2, char1);
if (cmp > 0) {
// char2 > char 1
} else if (cmp == 0) {
// char2 == char1
} else {
// char2 < char1
}
} else {
// char2 < char1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With