How to sort lines in C correctly?

Here is my code:

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

int cmp(const void *a, const void *b) {
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

void print_array(char **array, size_t len) {
    size_t i;
    for(i=0; i<len; i++) {
        printf("%s, ", array[i]);
    }
    putchar('\n');
}

int main(int argc, char *argv[]) {

        char *strings[] = { "z1.doc", "z100.doc",  "z2.doc", "z3.doc", "z20.doc"};
        size_t strings_len = sizeof(strings) / sizeof(char *);
        print_array(strings, strings_len);
        qsort(strings, strings_len, sizeof(char *), cmp);
        print_array(strings, strings_len);

        system("PAUSE");
        return 1;
}

actual conclusion

z1.doc, z100.doc, z2.doc, z20.doc, z3.doc

and I want him to be

z1.doc, z2.doc, z3.doc, z20.doc, z100.doc

What is doing wrong?

+3
source share
3 answers

Change your comparator to say:

return (atoi(*ib + 1) - atoi(*ia + 1));
+3
source

The actual output is correct, the string "z100.doc" is less than "z2.doc". Strcmp compares character by character and when it gets to "1" which is less than "2" and it stops there, so z100 <z2.

If you name the files z001.doc, z002.doc, z003.doc, z020.doc, z100.doc, they will be sorted the way you want.

+4
source

, ASCII, . . . , , ( ) , , - (, ), .

+1

Source: https://habr.com/ru/post/1721943/


All Articles