views:

103

answers:

6

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).

+4  A: 

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
}
David Knell
is there a way to compare it according to the numeric value of the string ? cause this is what i need for my comperisson
Nadav Stern
Yes - see above. If one string's longer or shorter than the other, then that alone determines the answer; if they're the same length, then an strcmp() can be used.
David Knell
A: 

It is ordered literally, which means that something starting on 9 will always be greater than something starting on 1. If you need to do an integer comparison, you'll have to use atoi.

Johan
i cant use atoi cause my string can have 10 chars inside it and the atoi / atol would not work
Nadav Stern
+3  A: 

If the strings have no leading/trailing garbage, use this algorithm:

  • Compare the lengths of the two strings using strlen(). The longer one is always the biggest.
  • If the length are equal, use strcmp().
schot
+1  A: 

You can convert a string to a 64-bit integer using _atoi64. Then, you can just compare them directly as you'd expect. Depending on your compiler, _atoi64 might be called something different.

Chris Schmich
+3  A: 

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.

You
you should have at least cached strlen() results in a variable.
Dummy00001
btw, I often do `int x = (strlen(a) - strlen(b));` as to spare one variable.
Dummy00001
+1  A: 

shortest way should be:

int mystrcmp(const char *a,const char *b)
{
  return strlen(a)-strlen(b)?strlen(a)-strlen(b):strcmp(a,b);
}