Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- /* ================================== CAR ====================================== */
- struct Car {
- const char *brand;
- const char *model;
- } Car;
- struct Car *car_new(const char *brand, const char *model) {
- struct Car *car = malloc(sizeof(Car));
- if(!car) {
- exit(EXIT_FAILURE);
- }
- car->brand = brand;
- car->model = model;
- return car;
- }
- /* ============================================================================= */
- /* ================================== CATALOG ================================== */
- #define MAX_CATALOG_SIZE 3
- struct Catalog {
- int number_of_contained_cars;
- struct Car *cars[];
- } Catalog;
- struct Catalog *catalog_new() {
- struct Catalog *catalog = malloc(sizeof(Catalog));
- for(int i=0; i<MAX_CATALOG_SIZE; i++) {
- // Qui alloco la memoria per le celle dell'array
- catalog->cars[i] = malloc(sizeof(Car));
- }
- return catalog;
- }
- bool catalog_is_full(struct Catalog catalog) {
- return catalog.number_of_contained_cars == MAX_CATALOG_SIZE;
- }
- void catalog_add(const struct Car *car, struct Catalog *catalog) {
- if(catalog_is_full(*catalog)) {
- printf("Catalog full");
- exit(EXIT_FAILURE);
- }
- *catalog->cars[catalog->number_of_contained_cars] = *car;
- catalog->number_of_contained_cars++;
- }
- void catalog_display(const struct Catalog *catalog) {
- for (int i=0; i<catalog->number_of_contained_cars; i++) {
- struct Car *car = catalog->cars[i];
- printf("%s | %s\n", car->brand, car->model);
- }
- }
- struct Catalog *catalog_load(char *file_path) {
- // Qui andrebbe la lettura da file, io per fare prima ho creato direttamente il catalogo
- // nel codice
- struct Catalog *catalog = catalog_new();
- struct Car *alfa = car_new("Alfa Romeo", "Giulia");
- struct Car *ferrari = car_new("Ferrari", "Enzo");
- catalog_add(alfa, catalog);
- catalog_add(ferrari, catalog);
- return catalog;
- }
- /* ===================================== MAIN ======================================= */
- int main() {
- struct Catalog *catalog = catalog_load("catalog.txt");
- printf("Catalog loaded.\n");
- int choice = 0;
- do {
- printf("\nWhat do you want to do?\n");
- printf("1- Display catalog\n");
- printf("2- Add car to catalog\n");
- scanf("%d", &choice);
- switch (choice) {
- case 1: catalog_display(catalog); break;
- case 2: {
- printf("Brand:\n");
- char *brand = malloc(sizeof(char *));
- scanf("%s", brand);
- printf("Model:\n");
- char *model = malloc(sizeof(char *));
- scanf("%s", model);
- struct Car *car = car_new(brand, model);
- catalog_add(car, catalog);
- } break;
- case 0: exit(EXIT_SUCCESS);
- default: exit(EXIT_SUCCESS);
- }
- } while (choice != 0);
- free(catalog);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement