solve exercise in c: Énoncé 1 Supposons qu'un fichier contienne les enregistrements…
- User
solve exercise in c: Énoncé 1 Supposons qu'un fichier contienne les enregistrements d'étudiants, chaque enregistrement contenant le nom et l'âge d'un étudiant. Écrivez un programme pour lire ces enregistrements et les afficher dans un ordre trié par nom. Exemple d'entrée/sortie: Entrer le nom de l'etudiant (fin pour arreter): toto Entrer l'age de l'etudiant: 18 Entrer le nom de l'etudiant (fin pour arreter): tata Entrer l'age de l'etudiant: 39 Entrer le nom de l'etudiant (fin pour arreter): titi Entrer l'age de l'etudiant: 20 Entrer le nom de l'etudiant (fin pour arreter): tyty Entrer l'age de l'etudiant: 17 Entrer le nom de l'etudiant (fin pour arreter): fin Name: tata age: 39 Name: titi age: 20 Name: toto age: 18 Name: tyty age: 17
- Assistant
Below is a C program that reads students' names and ages, then prints the records in alphabetical order. To implement this program, I will be using an array of structures to store the records and the
qsortfunction from the C Standard Library to sort them.#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STUDENTS 100 #define NAME_LENGTH 50 // Student structure typedef struct { char name[NAME_LENGTH]; int age; } Student; // Function to compare two students by name int compareStudents(const void *a, const void *b) { Student *studentA = (Student *)a; Student *studentB = (Student *)b; return strcmp(studentA->name, studentB->name); } int main() { Student students[MAX_STUDENTS]; int studentCount = 0; char inputName[NAME_LENGTH]; // Read student records while (1) { printf("Entrer le nom de l'etudiant (fin pour arreter): "); scanf("%s", inputName); if (strcmp(inputName, "fin") == 0) { break; } strncpy(students[studentCount].name, inputName, NAME_LENGTH); printf("Entrer l'age de l'etudiant: "); scanf("%d", &students[studentCount].age); studentCount++; } // Sort the student records qsort(students, studentCount, sizeof(Student), compareStudents); // Print the sorted student records printf("\nEtudiants triés par nom:\n"); for (int i = 0; i < studentCount; i++) { printf("Name: %s age: %d\n", students[i].name, students[i].age); } return 0; }