|
2
|
Programación / Programación C/C++ / Re: No Guarda la informacion mi programa
|
en: 28 Junio 2025, 09:49 am
|
No soy programador en C++, me he limitado a pasarlo por IA, para que opinase sobre el código // This C++ program implements a simple contact management system using a linked list, // allowing users to add, extract, delete, and display contacts along with sorting options. // However, it suffers from multiple issues including memory management with malloc/free, // lack of error handling, unused variables, lack of function documentation, and potential edge cases.
// Key improvement opportunities include: // - Replace `malloc` with `new` and `free` with `delete` for proper C++ memory management. // - Improve input validation to prevent processing invalid data. // - Enhance usability by adding more descriptive prompts and error messages. // - Refactor complex methods to improve readability and maintainability. // - Ensure all parts of the program use consistent data types and best practices.
#include "iostream" // For input and output operations #include "stdlib.h" // Standard library for memory allocation functions #include "fstream" // For file input and output operations #include "cstdlib" // Provides access to functions like rand() and malloc() using namespace std;
// Struct representing a contact with various attributes struct contacto { int ID; // Unique identifier for the contact char RFC[15]; // RFC field for the contact char nombre[30]; // Name of the contact char apellidos[30]; // Surname of the contact char telefono[15]; // Telephone number of the contact char celular[15]; // Cell phone number of the contact char correo[50]; // Email address of the contact char fecha[15]; // Birth date of the contact in DD/MM/AA format };
// Struct for linked list node, containing a contact and a pointer to the next node struct nodo { contacto info; // Contact information nodo *siguiente; // Pointer to the next node in the list };
nodo *raiz = NULL; // The head pointer of the linked list
// Function prototypes int vacia(); // Checks if the list is empty int cantidad(); // Returns the number of contacts in the list void insertar(int pos, contacto x); // Inserts a contact at a specified position void imprimir(); // Prints all contacts contacto extraer(int pos); // Extracts a contact from a specified position void borrar(int pos); // Deletes a contact at a specified position void intercambiar(int pos1, int pos2); // Swaps two contacts at specified positions void ordenamenormayor(); // Sorts contacts in ascending order by ID void ordenamayormenor(); // Sorts contacts in descending order by ID void menu(); // Displays the menu and handles user input void capturadato(contacto &dato); // Captures data for a contact void Imprimirdato(contacto dato); // Prints a specific contact's data void guarda(); // Saves the contacts to a file void Leer(); // Reads contacts from a file
int main() { Leer(); // Load contacts from the file at program start menu(); // Display the menu to the user return 0; // End of the program }
// Function to check if the list is empty int vacia() { return (raiz == NULL) ? 1 : 0; // Returns 1 if empty, otherwise returns 0 }
// Function to get the total number of contacts in the list int cantidad() { nodo *reco = raiz; // Start from the head of the linked list int cant = 0; // Initialize count while (reco != NULL) { // Traverse until the end of the list reco = reco->siguiente; // Move to the next node cant++; // Increment the count } return cant; // Return the total count of contacts }
// Function to insert a new contact at a specific position in the list void insertar(int pos, contacto x) { nodo *nuevo; // Pointer for the new node // IMPROVEMENT: Use new instead of malloc for C++ memory management nuevo = (nodo*) malloc(sizeof(nodo)); // Allocate memory for the new node nuevo->info = x; // Set the contact info for the new node
// Check if the position is valid for insertion if (pos <= cantidad() + 1) { if (pos == 1) { // Insert at the head nuevo->siguiente = raiz; // Point to the current head raiz = nuevo; // Update the head to the new node } else { // Navigate to the specified position nodo *reco = raiz; if (pos <= cantidad() + 1) { // If inserting at the end while (reco->siguiente != NULL) { // Traverse to the end reco = reco->siguiente; // Move to the next node } reco->siguiente = nuevo; // Link the new node at the end nuevo->siguiente = NULL; // Terminate the new node's next pointer } else { // Insert in the middle for (int i = 1; i <= pos - 2; i++) { // Navigate to the insertion point reco = reco->siguiente; } nodo *sig = reco->siguiente; // Save the current next node reco->siguiente = nuevo; // Link the new node nuevo->siguiente = sig; // Link the saved node after the new node } } } else { // IMPROVEMENT: Handle invalid insertion positions cout << "Posición inválida para insertar" << endl; // NEEDS TO HANDLE INVALID OPTIONS PROPERLY } }
// Function to print all contacts in the list void imprimir() { nodo *reco = raiz; // Start from the head of the linked list if (vacia() == 1) { // Check if the list is empty cout << "Lista está vacía: " << endl; // Notify user } else { cout << "Lista está completa: " << endl; // Notify user while (reco != NULL) { // Traverse and print each contact Imprimirdato(reco->info); // Print contact information reco = reco->siguiente; // Move to the next node } cout << endl; // New line at the end of output } }
// Function to extract a contact from a specified position contacto extraer(int pos) { contacto informacion; // Variable to store the extracted contact info // Check if the position is valid for extraction if (pos <= cantidad()) { nodo *bor; // Pointer to be deleted if (pos == 1) { // Extract from the head informacion = raiz->info; // Store information from the head bor = raiz; // Pointer to be deleted raiz = raiz->siguiente; // Update head to the next node } else { nodo *reco = raiz; // Start from head to find the contact for (int i = 1; i <= pos - 2; i++) { // Navigate to one before the target reco = reco->siguiente; // Move to the next node } nodo *prox = reco->siguiente; // Pointer to the contact to be deleted reco->siguiente = prox->siguiente; // Link to the next of the contact to be deleted bor = prox; // Holds the contact to be deleted } // IMPROVEMENT: Use delete instead of free for C++ memory management free(bor); // Delete the node from memory return informacion; // Return the extracted contact info } // IMPROVEMENT: Handle the case where position is invalid cout << "Posición inválida para extracción" << endl; // Notify user // NEEDS TO HANDLE INVALID EXTRACTION PROPERLY }
// Function to delete a contact at a specified position void borrar(int pos) { // Check if the position is valid for deletion if (pos <= cantidad()) { nodo *bor; // Node to be free if (pos == 1) { // Remove from head bor = raiz; // Node to be deleted raiz = raiz->siguiente; // Update head to the next node } else { nodo *reco = raiz; // Start from head to find the contact for (int i = 1; i <= pos - 2; i++) { // Navigate to one before the target reco = reco->siguiente; } nodo *prox = reco->siguiente; // Pointer to the contact to be deleted bor = prox; // Holds the contact to be deleted reco->siguiente = prox->siguiente; // Remove the pointer to the contact to be deleted } // IMPROVEMENT: Use delete instead of free for C++ memory management free(bor); // Free the memory occupied by the deleted node } // IMPROVEMENT: Handle the case where position is invalid else { cout << "Posición inválida para borrar." << endl; // Notify user // NEEDS TO HANDLE INVALID DELETION PROPERLY } }
// Function to swap two contacts at specified positions void intercambiar(int pos1, int pos2) { // Check if both positions are valid if (pos1 <= cantidad() && pos2 <= cantidad()) { nodo *reco1 = raiz; // Start from head to find first contact for (int f = 1; f < pos1; f++) { // Navigate to first contact reco1 = reco1->siguiente; } nodo *reco2 = raiz; // Start from head to find second contact for (int f = 1; f < pos2; f++) { // Navigate to second contact reco2 = reco2->siguiente; } // Swap the information of the two contacts contacto aux = reco1->info; // Temporary storage of info from first contact reco1->info = reco2->info; // Assign second contact's info to the first reco2->info = aux; // Assign stored info to the second contact } // IMPROVEMENT: Handle the case where one or both positions are invalid else { cout << "Posiciones inválidas para intercambio." << endl; // Notify user // NEEDS TO HANDLE INVALID INTERCHANGE PROPERLY } }
// Function to sort contacts in ascending order by ID void ordenamenormayor() { nodo *reco1 = raiz; // Start from the head of the list nodo *reco2; // Pointer for nested traversal // Traverse each element with nested traversal to sort while (reco1 != NULL) { reco2 = reco1->siguiente; // Start comparing with next elements while (reco2 != NULL) { if (reco2->info.ID < reco1->info.ID) { // Compare IDs for sorting // Swap the contact info if out of order contacto aux = reco2->info; // Temporary storage reco2->info = reco1->info; // Replace info reco1->info = aux; // Save the original info back to first } reco2 = reco2->siguiente; // Move to next node } reco1 = reco1->siguiente; // Move to the next node to sort } }
// Function to sort contacts in descending order by ID void ordenamayormenor() { nodo *reco1 = raiz; // Start from head for outer loop nodo *reco2; // Pointer for inner loop // Nested traversal to sort contacts while (reco1 != NULL) { reco2 = reco1->siguiente; // Start comparing with subsequent contacts while (reco2 != NULL) { if (reco2->info.ID > reco1->info.ID) { // Check for reverse order // Swap the contact info if out of order contacto aux = reco2->info; // Temporary storage reco2->info = reco1->info; // Swap info reco1->info = aux; // Restore original info } reco2 = reco2->siguiente; // Move to the next node } reco1 = reco1->siguiente; // Move to the next node to sort } }
// Function to capture data for a new contact void capturadato(contacto &dato) { system("cls"); // Clear console for better visibility cout << "Datos de contacto: " << endl; // Prompt for user input cout << "ID: "; cin >> dato.ID; // Read contact ID cin.get(); // Clear input buffer cout << "RFC: "; cin.getline(dato.RFC, 15); // Read RFC cout << "Nombre: "; cin.getline(dato.nombre, 30); // Read name cout << "Apellidos: "; cin.getline(dato.apellidos, 30); // Read surname cout << "Telefono: "; cin.getline(dato.telefono, 15); // Read telephone cout << "Celular: "; cin.getline(dato.celular, 15); // Read celular cout << "Correo electronico: "; cin.getline(dato.correo, 50); // Read email cout << "Fecha de nacimiento: (DD/MM/AA) "; cin.getline(dato.fecha, 15); // Read birth date }
// Function to print a specific contact's data void Imprimirdato(contacto dato) { cout << "ID: " << dato.ID << endl; // Print contact ID cout << "RFC: " << dato.RFC << endl; // Print RFC cout << "Nombre: " << dato.nombre << endl; // Print name cout << "Apellidos: " << dato.apellidos << endl; // Print surname cout << "Telefono: " << dato.telefono << endl; // Print telephone cout << "Celular: " << dato.celular << endl; // Print celular cout << "Correo electronico: " << dato.correo << endl; // Print email cout << "Fecha de nacimiento: " << dato.fecha << endl; // Print birth date }
// Function to save contacts to a file void guarda() { nodo *reco = raiz; // Start from the head of the linked list FILE *archivo; // File pointer archivo = fopen("Agenda de contactos.txt", "wt+"); // Open file for writing // Write each contact to the file while (reco != NULL) { fwrite(&reco->info, sizeof(reco->info), 1, archivo); // Write contact info reco = reco->siguiente; // Move to next node } fclose(archivo); // Close the file }
// Function to read contacts from a file void Leer() { char cadena[30], cadena15[15]; // Temporary char arrays (unused) contacto recupera; // Variable to hold extracted contact information FILE *archivo; // File pointer archivo = fopen("Agenda de contactos.txt", "at+"); // Open file for appending // Read each contact from the file and insert into the list while (fread(&recupera, sizeof(recupera), 1, archivo) == 1) { insertar(1, recupera); // Always insert at position 1 for easier sorting } fclose(archivo); // Close the file ordenamayormenor(); // Sort contacts in descending order by ID after loading }
// Main menu function for user interaction void menu() { int opc = 0; // Variable to store user option while (opc != 9) { // Loop until exit option system("cls"); // Clear the console cout << "1. Agregar a la agenda" << endl; // Option to add a contact cout << "2. Extraer contacto" << endl; // Option to extract a contact cout << "3. Borrar contacto" << endl; // Option to delete a contact cout << "4. Imprimir la lista" << endl; // Option to print all contacts cout << "5. Ordenar de mayor a menor" << endl; // Option to sort contacts cout << "6. Ordenar de menor a mayor" << endl; // Option to sort contacts cout << "7. Cantidad de contactos" << endl; // Option to show count of contacts cout << "8. Mover contactos" << endl; // Option to swap contacts cout << "9. Guardar y salir" << endl; // Option to save and exit cout << "\n\n\n"; // Extra new lines for spacing cout << "Elige una opcion...." << endl; // Prompt for user choice cin >> opc; // Read user option cin.get(); // Clear input buffer
switch (opc) { case 1: { // Add a contact system("cls"); // Clear console contacto dato; // Temporary variable for new contact int pos; // Variable to store position capturadato(dato); // Capture data for the new contact cout << "Que posicion desea insertar" << endl; cin >> pos; // Get desired position insertar(pos, dato); // Insert contact at specified position cout << "Contacto agregado." << endl; // Notify user cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 2: { // Extract a contact system("cls"); // Clear console int pos; // Variable to store position if (vacia() == 1) { // Check if the list is empty cout << "Lista vacia : " << endl; // Notify user } else { cout << "El contacto a extraer es: "; // Prompt for position cin >> pos; // Read position cin.get(); // Clear buffer cout << "Extrayendo el contacto : " << endl; Imprimirdato(extraer(pos)); // Extract and print contact information } cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 3: { // Delete a contact system("cls"); // Clear console int pos; // Variable to store position if (vacia() == 1) { // Check if list is empty cout << "Lista vacia : " << endl; // Notify user } else { cout << "Posición a borrar: "; // Prompt for position cin >> pos; // Read position cin.get(); // Clear buffer borrar(pos); // Delete contact at specified position cout << "Eliminado \n"; // Notify user } cout << "Precione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 4: { // Print the list of contacts system("cls"); // Clear console imprimir(); // Print all contacts cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 5: { // Order contacts from largest to smallest system("cls"); // Clear console if (vacia() == 1) { // Check if the list is empty cout << "Lista vacia : " << endl; // Notify user } else { ordenamenormayor(); // Call sort function cout << "Lista ha sido ordenada \n"; // Notify user } cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 6: { // Order contacts from smallest to largest system("cls"); // Clear console if (vacia() == 1) { // Check if the list is empty cout << "Lista vacia : " << endl; // Notify user } else { ordenamayormenor(); // Call sort function cout << "Lista ordenada\n"; // Notify user } cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 7: { // Show quantity of contacts system("cls"); // Clear console if (vacia() == 1) { // Check if the list is empty cout << "Lista vacia : " << endl; // Notify user } else { cout << "Número de contactos: " << cantidad() << endl; // Show count } cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 8: { // Move (swap) contacts system("cls"); // Clear console int pos1, pos2; // Variables for positions to be swapped if (vacia() == 1) { // Check if the list is empty cout << "1er contacto a intercambiar: "; // Ask for first position cin >> pos1; // Read position cin.get(); // Clear buffer cout << "2do contacto a intercambiar: "; // Ask for second position cin >> pos2; // Read position cin.get(); // Clear buffer intercambiar(pos1, pos2); // Perform swap imprimir(); // Show updated list } else { cout << "Lista vacia : " << endl; // Notify user } cout << "Precione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } case 9: { // Save and exit system("cls"); // Clear console cout << "Guardando agenda...\n"; // Notify user guarda(); // Save all contacts cout << "Operación exitosa.\nPresione cualquier tecla para continuar" << endl; // Notify user cin.get(); // Clear buffer break; // Exit case } default: { // Handle invalid options system("cls"); // Clear console cout << "Opción no válida\n"; // Notify user cout << "Presione cualquier tecla para continuar"; // Prompt to continue cin.get(); // Clear buffer break; // Exit case } } } }
Herramienta: https://products.aspose.ai/total/es/ai-code-analysis/cpp
|
|
|
7
|
Informática / Hardware / Re: Ordenador 8th i7
|
en: 12 Junio 2025, 19:46 pm
|
Yo actualicé mi HP de 8Gb a 16 Gb, tenía un banco libre, con lo cual fue rápido y económico. En mi caso , habia varios HP con el mismo nombre, pero con diferentes características, tienes que mirar por el número de producto, y no por el nombre. Otra forma más simple, es desmontándolo, tarde o temprano te tocará hacerlo. Lo compre en Amazon, asegúrate que sea compatible.
|
|
|
8
|
Informática / Hardware / Re: Ordenador 8th i7
|
en: 12 Junio 2025, 08:48 am
|
Y cuanta memoria RAM física posee? Si tiene poca memoria RAM puede ser que Windows utilice RAM virtual, en este caso emplea el disco duro como RAM.
|
|
|
|
|
|
|