This C++ code is a program that parses a user...

August 27, 2025 at 03:12 PM

#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <memory> // Classe base class Log { public: virtual ~Log() = default; virtual void stampa() const = 0; }; // Cliente class Cliente : public Log { public: std::string nome; std::string cognome; std::string email; int puntiFedelta{0}; void stampa() const override { std::cout << "Cliente: " << nome << " " << cognome << " (" << email << ") - Punti: " << puntiFedelta << "\n"; } }; // Ordine class Ordine : public Log { public: std::string prodotto; std::string cid; int quantita{0}; double prezzo{0.0}; void stampa() const override { double stima = quantita * prezzo; std::cout << "[" << cid << "] " << prodotto << " Quantita: " << quantita << " Prezzo: " << prezzo << " -> Stima valore totale: " << stima << " €\n"; } }; int main() { std::string scelta; std::cout << "Vuoi leggere Cliente ordine Ordine?\n"; std::getline(std::cin, scelta); std::vector<std::unique_ptr<Log>> logs; if (scelta == "Cliente" || scelta == "cliente") { std::ifstream file("clienti.txt"); if (!file) { std::cerr << "Errore apertura file clienti.txt\n"; return 1; } std::string line; while (std::getline(file, line)) { std::istringstream iss(line); auto cliente = std::make_unique<Cliente>(); if (iss >> cliente->nome >> cliente->cognome >> cliente->email >> cliente->puntiFedelta) { logs.push_back(std::move(cliente)); } else { std::cerr << "Riga malformata in clienti.txt: " << line << "\n"; } } } else if (scelta == "Ordine" || scelta == "ordine") { std::ifstream file("ordini.txt"); if (!file) { std::cerr << "Errore apertura file ordini.txt\n"; return 1; } std::string line; while (std::getline(file, line)) { std::istringstream iss(line); auto ordine = std::make_unique<Ordine>(); if (iss >> ordine->cid >> ordine->prodotto >> ordine->quantita >> ordine->prezzo) { logs.push_back(std::move(ordine)); } else { std::cerr << "Riga malformata in ordini.txt: " << line << "\n"; } } std::string criterio; std::cout << "Vuoi ordinare per (quantita) ordine (prezzo)? "; std::getline(std::cin, criterio); if (criterio == "Quantita" || criterio == "quantita") { std::sort(logs.begin(), logs.end(), [](const auto& Attuale, const auto& Prossimo) { auto* oAttuale = dynamic_cast<Ordine*>(Attuale.get()); auto* oProssimo = dynamic_cast<Ordine*>(Prossimo.get()); return oAttuale && oProssimo && oAttuale->quantita < oProssimo->quantita; }); } else if (criterio == "Prezzo" || criterio == "prezzo") { std::sort(logs.begin(), logs.end(), [](const auto& Attuale, const auto& Prossimo) { auto* oAttuale = dynamic_cast<Ordine*>(Attuale.get()); auto* oProssimo = dynamic_cast<Ordine*>(Prossimo.get()); return oAttuale && oProssimo && oAttuale->prezzo < oProssimo->prezzo; }); } } else { std::cout << "Scelta non valida.\n"; return 1; } // Stampa polimorfica for (const auto& log : logs) { log->stampa(); } return 0; }

This C++ code is a program that parses a user selection to either read customer data from "clienti.txt" or order data from "ordini.txt," processes the data, sorts it optionally for orders, and then displays the details in the console. Here's a detailed explanation:

Key Features and Workflow:

  1. Abstract Base Class (Log):

    • Provides a virtual function stampa() for polymorphic behavior. Both Cliente and Ordine classes inherit from this and implement their own version of stampa().
  2. Cliente Class:

    • Represents a customer with attributes such as nome (name), cognome (surname), email, and puntiFedelta (loyalty points).
    • Its stampa() function prints the customer's details in a formatted manner.
  3. Ordine Class:

    • Represents an order with attributes such as prodotto (product name), cid (client ID), quantita (quantity), and prezzo (price).
    • Its stampa() function prints order details along with a calculated estimated total value (quantita * prezzo).
  4. Main Function Execution:

    • Asks the user whether they want to view "Cliente" (customers) or "Ordine" (orders).
    • Based on the choice:
      • For Cliente:
        • Opens the file clienti.txt (expected format in each line: nome cognome email puntiFedelta), parses this data, and stores it in logs as smart pointers (std::unique_ptr) to Cliente objects.
      • For Ordine:
        • Opens the file ordini.txt (expected format in each line: cid prodotto quantita prezzo), parses this data, and stores it in logs as smart pointers (std::unique_ptr) to Ordine objects.
        • Prompts the user to input a sorting criterion: either "quantita" (quantity) or "prezzo" (price).
        • Data is sorted using std::sort based on the specified criterion using dynamic casting for comparison of Ordine objects.
  5. Polymorphic Display:

    • Iterates through the logs container and calls the stampa() method on each object. This polymorphic behavior ensures the correct stampa() method is invoked, either from Cliente or Ordine.
  6. Error Handling:

    • Validates the files (clienti.txt or ordini.txt) can be opened. If not, it prints an error and exits.
    • Handles malformed lines in the input files (e.g., lines that don't meet the expected data format).

Example Behavior:

  • If the user selects Cliente, the program reads the file clienti.txt, processes the data to construct a list of Cliente objects, and displays their details.
  • If the user selects Ordine, the program reads the file ordini.txt, processes the data into Ordine objects, prompts for sorting (either by quantita or prezzo), applies the sorting, and displays the sorted data.

Key Aspects Handled:

  1. Dynamic Polymorphism with Smart Pointers:

    • Uses std::unique_ptr for memory management, avoiding manual delete calls.
    • The Log base class ensures both Cliente and Ordine are handled uniformly when stored in the same container.
  2. User Interaction:

    • Prompts the user for choices (Cliente/Ordine, sorting criteria).
    • Ensures user inputs are interpreted case-insensitively (cliente and Cliente are treated the same, for example).
  3. File Operations:

    • Reads two potential text files (clienti.txt and ordini.txt) and processes line-by-line input according to the expected formats.
  4. Sorting with Comparison Logic:

    • For Ordine objects, sorting is done dynamically via lambda functions that use dynamic_cast to safely cast from the Log base class to Ordine.

Errors or Shortcomings:

  • The program assumes that clienti.txt and ordini.txt exist and are accessible in the program's directory.
  • The fields in the files must be correctly formatted; otherwise, the program will skip malformed lines.
  • There is no mechanism to add additional choices or operations at runtime without modifying the code.

General Output of the Program:

The exact output depends on the user's choice, the input data in the respective files, and the optional sorting criteria for Ordine. For example:

clienti.txt:

John Doe johndoe@example.com 120
Jane Smith janesmith@example.com 95

ordini.txt:

C001 Laptop 2 500.0
C002 Phone 5 200.0
C003 Mouse 10 25.0

User selects Cliente:

Cliente: John Doe (johndoe@example.com) - Punti: 120
Cliente: Jane Smith (janesmith@example.com) - Punti: 95

User selects Ordine and sorts by Prezzo:

[C003] Mouse Quantita: 10 Prezzo: 25 -> Stima valore totale: 250 €
[C002] Phone Quantita: 5 Prezzo: 200 -> Stima valore totale: 1000 €
[C001] Laptop Quantita: 2 Prezzo: 500 -> Stima valore totale: 1000 €
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node