Answer the question
In order to leave comments, you need to log in
How to sort strings alphabetically in SI?
Here is the assignment I am doing:
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;
}
Answer the question
In order to leave comments, you need to log in
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);
}
qsort(МАССИВ_СТРУКТУР, РАЗМЕР_МАССИВА, sizeof(price), &compare_prices);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question