Skip to content

Instantly share code, notes, and snippets.

@MatonAnthony
Created January 21, 2016 13:31
Show Gist options
  • Save MatonAnthony/e9db0b01016316895504 to your computer and use it in GitHub Desktop.
Save MatonAnthony/e9db0b01016316895504 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAILLE 5
typedef enum Categorie {
BOISSONS, BUREAU, CONSERVES, DEJEUNER, DIVERS, EPICES, FECULENTS, FRAIS, HYGIENE, MENAGE,
PATISSERIE, PHARMACIE, SURGELES
} Categorie;
typedef struct Achat {
char aAcheter[25];
double quantite;
double prixUnitaire;
Categorie rayon;
} Achat;
Achat decoupe(char *);
int ajout(Achat, Achat **);
int cmpAchat(Achat *, Achat *);
void afficheParRayon(Achat *, int);
int main(){
Achat **table;
int tailleLogique = 0;
char ligne[256];
while(fgets(ligne, 256, stdin) != NULL){
Achat monAchat = decoupe(ligne);
tailleLogique = ajout(monAchat, table);
}
qsort(table, TAILLE, sizeof(Achat), (int (*) (const void *, const void *)) cmpAchat);
afficheParRayon(*table, tailleLogique);
}
Achat decoupe(char *string){
// Il est assumé que le champ fournit sera toujours complet !
Achat monAchat;
strcpy(monAchat.aAcheter, strtok(string, "\t "));
monAchat.quantite = atof(strtok(NULL, "\t "));
monAchat.prixUnitaire = atof(strtok(NULL, "\t "));
monAchat.rayon = (Categorie) strtok(string, "\t ");
return monAchat;
}
int ajout(Achat monAchat, Achat **table){
static int tailleLogique = 0;
static int taillePhysique = TAILLE;
if(tailleLogique == 0){
if((*table = malloc(TAILLE * sizeof(Achat))) == NULL){
perror("Malloc KO");
return -1;
}
}
if(tailleLogique == taillePhysique){
if((*table = realloc(table, ((taillePhysique *= 2) * sizeof(Achat)))) == NULL){
perror("Realloc KO");
return -1;
}
}
*table[tailleLogique] = monAchat;
return ++tailleLogique;
}
int cmpAchat(Achat *comparant, Achat *compare){
return (comparant->rayon - compare->rayon);
}
void afficheParRayon(Achat *liste, int taille){
printf("Nombre total d'articles : %d\n", taille);
Achat *baladeur;
for(baladeur = liste; baladeur - liste < taille; baladeur++){
printf("%0.f \t %s \n", baladeur->quantite, baladeur->aAcheter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment