N
N
nkorobkov2016-06-05 18:25:42
C++ / C#
nkorobkov, 2016-06-05 18:25:42

How to sort strings alphabetically in SI?

Here is the assignment I am doing:
4d014b388a49499189ffb1599fb30ef5.png
Here is the program I have written so far:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct price{
    char name[30];
    char shop[30];
    char product_price[10];
};
int main(){
    struct price product[8];
    char check[30];
    int i, compare_limit = 30;
    char memory[30];

    //Ввод информации в структуру с товарами
    for( i = 0; i < 2; i++ ){
        printf("Enter product %d NAME:\n", i);
        fgets( product[i].name, 30, stdin );
        /*printf("Enter product %d SHOP:\n", i);
        fgets( product[i].shop, 30, stdin );
        printf("Enter product %d PRICE:\n", i);
        fgets( product[i].product_price, 10, stdin );*/
    }

    for( i = 0; i < 2; i++){
        if(product[i+1].name > product[i].name){
            strcpy(memory, product[i].name);
            strcpy(product[i].name, product[i+1].name);
            strcpy(product[i+1].name, memory);
        }
    }

    for( i = 0; i < 2; i++ ){
        printf("%s\n", product[i].name);
    }

    //Вывод информации о товаре по его имени
    while ( 1 ){
        printf("You can get information about any product by enter it's name:\n");
        fgets( check, 30, stdin );
        for( i = 0; i < 2; i++ ){
            if( strncmp(check, product[i].name, compare_limit) == 0 ){
                printf("Product %d NAME is: %s", i, product[i].name);
                printf("Product %d SHOP is: %s", i, product[i].shop);
                printf("Product %d PRICE is: %s", i, product[i].product_price);
            }
        }
    }
    return 0;
}

It seems that I implemented everything (probably not very competently), except for sorting the records in alphabetical order. I don't know if I'm comparing strings correctly and what principle of comparison they have in general (A > a, b < a, B > a) ... please tell me how it all works and how can I sort the strings?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2016-06-05
@nkorobkov

You need to use qsort .
Comparison function:

int compare_prices(const void* price1, const void* price2) {
    const char* name1 = ((const price*)price1)->name;
    const char* name2 = ((const price*)price2)->name;
    return strcmp(name1, name2);
}

Calling qsort:
qsort(МАССИВ_СТРУКТУР, РАЗМЕР_МАССИВА, sizeof(price), &compare_prices);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question