Сортировка массива элементов Struct в зависимости от имени - PullRequest
0 голосов
/ 05 мая 2020

Я с sh кто-нибудь может мне помочь. Я новичок в программировании, и моя проблема в том, что я пытаюсь отсортировать по алфавиту разные элементы struct в зависимости от того, какая из них является первой буквой имени, введенного в этом struct item . Я пробовал разные вещи, но застрял здесь.

Я вставил сюда написанный мной код. Я прокомментировал ту часть, в которой помогаю, и, поскольку мне нужно, чтобы программа была на испанском языке sh, некоторые части моего кода написаны на этом языке. Надеюсь, это не проблема для понимания того, что я пытаюсь сделать.

PD. Если вы, ребята, дадите мне несколько советов по улучшению моих навыков, было бы здорово. Заранее спасибо.

#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXNOMBRE 15
#define MAXAPELLIDO 15
#define MAXDIRECCION 30
#define MAXTEL 12
#define MAXALUMNOS 4


struct Alumno
{
    char nombre[MAXNOMBRE];
    char apellido[MAXAPELLIDO];
    char direccion[MAXDIRECCION];
    int edad;
    char telefono[MAXTEL];
} alumnos[MAXALUMNOS], alumnos_cpy[1]; 

int main()
{
    int contador=0, i=0, j=0, k;
    char seleccion;


    system("CLS");

    do
    {
        printf("BIENVENIDO AL REGISTRO\n");
        printf("a) Registrar alumno\n");
        printf("b) Mostrar alumnos\n");
        printf("c) Salir\n");
        scanf("%s", &seleccion);

        switch (seleccion)
        {
            case 'A': case 'a':
                if (contador < MAXALUMNOS)
                {   
                    printf("Lugares Disponibles: <%d>\n", MAXALUMNOS-contador);
                    printf("Numero de alumnos que desee registrar: ");
                    fflush(stdin);
                    scanf("%d", &j);

                    for (i = 0; i < j; i++)
                    {
                        printf("\n");

                        printf("Ingrese el nombre del alumno: ");
                        fflush(stdin);
                        gets(alumnos[contador].nombre);
                        printf("Ingrese el apellido del alumno: ");
                        fflush(stdin);
                        gets(alumnos[contador].apellido);
                        printf("Ingrese direccion (calle y numero): ");
                        fflush(stdin);
                        gets(alumnos[contador].direccion);
                        printf("Ingrese edad: ");
                        fflush(stdin);
                        scanf("%d", &alumnos[contador].edad);
                        printf("Ingrese telefono: ");
                        fflush(stdin);
                        gets(alumnos[contador].telefono);
                        contador++;

                        printf("\n");
                    }
                }
                else
                {
                    printf("La memoria ya esta llena!\n");
                }

                //ALPHABETICALLY SORTING
                //ALPHABETICALLY SORTING
                //ALPHABETICALLY SORTING
                for (i = 0; i <= contador-1; i++)
                {   
                    if (alumnos[i].nombre[0] > alumnos[i+1].nombre[0])
                    {

                        // memcpy(&alumnos_cpy[0], &alumnos[i], sizeof(alumnos[i]));
                        // memcpy(&alumnos[i], &alumnos[i+1], sizeof(alumnos[i+1]));
                        // memcpy(&alumnos[i+1], &alumnos_cpy[0], sizeof(alumnos_cpy[0]));
                        // //alumnos_cpy[0] = alumnos[i];
                        // //alumnos[i] = alumnos[i+1];
                        // //alumnos[i+1] = alumnos_cpy[0];
                    }
                }
                //ALPHABETICALLY SORTING
                //ALPHABETICALLY SORTING
                //ALPHABETICALLY SORTING


                printf("\nPresione Enter para continuar...");
                break;


            case 'B': case 'b':
                for (i = 0; i < contador; i++)
                {
                    printf("\n\nAlumno %d", i+1);
                    printf("\nNombre: %s %s", alumnos[i].nombre, alumnos[i].apellido);
                    printf("\nDireccion: %s", alumnos[i].direccion);
                    printf("\nEdad: %d", alumnos[i].edad);
                    printf("\nTelefono: %s", alumnos[i].telefono);
                }

                printf("\nPresione Enter para continuar...");
                break;

            case 'C': case 'c':
                printf("Presione Enter para salir...");
                break;

            default:
                printf("Seleccion Incorrecta - Intente de Nuevo\n");
                printf("Presione Enter para continuar...");
                break;

        }

        getch();
        system("CLS");

    } while (seleccion != 'C' && seleccion != 'c');


    printf("\n");
    getch();
    return 0;
}

1 Ответ

0 голосов
/ 05 мая 2020

Вместо того, чтобы вручную копировать всю структуру, вы можете использовать qsort, чтобы сделать работу за вас. Вы могли бы просто написать вспомогательную функцию, которая возвращает -1, 0 или 1. Функция qsort выполнит остальную часть logi c.

// qsort helper function
int alumno_sort(void *p1, void *p2) {
    struct Alumno *a1 = p1, *a2 = p2;
    return strcasecmp(a1->nombre, a2->nombre);
}

// actually sorting
qsort(alumnos, contador, sizeof *alumnos, alumno_sort);

Другой способ приблизиться к этому - поставить ваши структуры, например, в связанном списке вместо массива. Затем вы можете поменять местами ссылки на другие элементы, чтобы отсортировать список.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...