👾 Una biblioteca en C: aprender programando / A Library in C: Learning by Coding 👾
Español
¡Hola, comunidad de Hive!
Hoy quiero compartir un proyecto educativo que permite conectar la programación con una situación cotidiana: la administración de una biblioteca. Se trata de un programa desarrollado en C++ que funciona desde la consola y permite registrar usuarios, organizar materiales, consultar libros y gestionar préstamos, devoluciones y reservas.
Lo interesante de este ejercicio no está solamente en conseguir que aparezca un menú en pantalla. También consiste en comprender cómo se relacionan los datos y qué comprobaciones necesita cada operación para producir resultados coherentes.
Antes de presentar esta versión, revisé su funcionamiento y corregí varios aspectos relacionados con las entradas, los identificadores y el inventario. Este proceso demuestra que programar también implica revisar, detectar problemas y mejorar nuestras primeras soluciones.
English
Hello, Hive community!
Today I want to share an educational project that connects programming with an everyday situation: managing a library. It is a console-based program developed in C++ that lets users register people, organize materials, search for books, and manage loans, returns, and reservations.
What makes this exercise interesting is not simply getting a menu to appear on the screen. It also involves understanding how the data connects and which checks each operation needs to produce consistent results.
Before presenting this version, I reviewed its behavior and corrected several issues involving input, identifiers, and inventory. This process shows that programming also means reviewing our work, identifying problems, and improving our first solutions.
🧩 Estructuras y organización / Structures and Organization
El programa parte de tres estructuras principales: Material, Usuario y Prestamo. Cada una representa una parte del sistema y reúne los datos necesarios para trabajar con ella.
Material almacena información como el código, título, autor, género, año de publicación y cantidad de ejemplares. Usuario contiene el carnet, los datos personales, el tipo de usuario y la cantidad de libros prestados. Finalmente, Prestamo relaciona a una persona con un material y registra las fechas y el estado de la operación.
Los registros se almacenan en vectores. A partir de ellos, las funciones buscan usuarios y materiales mediante sus identificadores. Esta organización ayuda a entender que una aplicación no es una colección de instrucciones aisladas: sus componentes necesitan compartir información y mantener relaciones claras.
Además, cada tarea tiene una función específica. Por ejemplo, registrarUsuario() incorpora personas, registrarMaterial() amplía el catálogo y verCatalogoGeneral() muestra los materiales registrados. El menú principal se encarga de recibir la opción elegida y llamar a la función correspondiente.
The program starts with three main structures: Material, Usuario, and Prestamo. Each represents a part of the system and groups the information needed to work with it.
Material stores details such as the code, title, author, genre, publication year, and number of copies. Usuario contains the library card identifier, personal information, user type, and number of borrowed books. Finally, Prestamo connects a person to a material and records the dates and status of the transaction.
The records are stored in vectors. Functions search these collections for users and materials through their identifiers. This organization helps explain that an application is not a collection of isolated instructions: its components need to share information and maintain clear relationships.
Each task also has its own function. For example, registrarUsuario() adds people, registrarMaterial() expands the catalog, and verCatalogoGeneral() displays the registered materials. The main menu receives the selected option and calls the corresponding function.
📚 Consultas y préstamos / Searches and Loans
Una biblioteca necesita facilitar la consulta de sus materiales. Para ello, buscarMaterial() permite encontrar coincidencias en el código, título, autor o género. La búsqueda conserva una característica que conviene conocer: distingue entre mayúsculas y minúsculas, por lo que escribir una palabra de forma diferente puede cambiar los resultados.
La función realizarPrestamo() concentra varias reglas definidas para este proyecto. Los estudiantes pueden mantener hasta cinco préstamos activos y el personal hasta doce. También existen materiales exclusivos para el personal, mientras que las publicaciones anteriores a 1958 quedan destinadas a consulta interna.
Antes de autorizar una operación, se comprueba que existan el usuario y el material, que se respeten las restricciones y que la persona no haya alcanzado su límite. También se evita que un usuario tenga dos préstamos activos del mismo título.
Cuando se aprueba el préstamo, el programa registra la operación, reduce las copias disponibles y aumenta el contador del usuario. Estas acciones deben permanecer sincronizadas para representar correctamente lo que sucede.
A library needs to make its materials easy to find. For this purpose, buscarMaterial() searches for matches in the code, title, author, or genre. One detail is worth noting: the search is case-sensitive, so entering a word with different capitalization may change the results.
The realizarPrestamo() function brings together several rules defined for this project. Students can have up to five active loans, while staff members can have up to twelve. Some materials are restricted to staff, and publications from before 1958 are available for in-library consultation only.
Before approving a transaction, the program checks that the user and material exist, that the restrictions are respected, and that the person has not reached their borrowing limit. It also prevents a user from having two active loans for the same title.
Once a loan is approved, the program records the transaction, reduces the available copies, and increases the user's borrowing count. These actions must remain synchronized to accurately represent what is happening.
🔄 Reservas y devoluciones / Reservations and Returns
Las reservas permiten estudiar otra parte del programa: el uso de una queue<string>. Cada material tiene una cola donde se guardan los carnets de quienes esperan una copia, respetando su orden de llegada.
En esta versión, la reserva no desaparece cuando alguien devuelve un ejemplar. Permanece hasta que su titular concreta el préstamo o la cancela. Además, se impiden las reservas duplicadas y se respeta la prioridad de la primera persona en la cola.
La función realizarDevolucion() busca un préstamo activo que coincida con el carnet y el código introducidos. Si lo encuentra y los contadores son coherentes, registra la fecha de devolución, cierra el préstamo y actualiza las existencias y el contador del usuario.
Aquí aparece una idea fundamental: la consistencia. No basta con aumentar o disminuir un número; el inventario, el historial y los datos del usuario deben reflejar la misma situación.
Si hay una reserva pendiente y vuelve a existir disponibilidad, el programa muestra un aviso en la consola. Ese aviso es una simulación: no envía correos ni mensajes externos.
Reservations provide an opportunity to study another part of the program: the use of a queue<string>. Each material has a queue that stores the library card identifiers of people waiting for a copy, preserving their order of arrival.
In this version, a reservation does not disappear when someone returns a copy. It remains until its holder completes the loan or cancels it. Duplicate reservations are also prevented, and the first person in the queue keeps priority.
The realizarDevolucion() function searches for an active loan matching the entered user identifier and material code. If it finds one and the counters are consistent, it records the return date, closes the loan, and updates both the inventory and the user's borrowing count.
This introduces a fundamental idea: consistency. Increasing or decreasing a number is not enough; the inventory, loan history, and user information must all reflect the same situation.
If a reservation is pending and a copy becomes available, the program displays a console notice. This notice is a simulation: it does not send emails or external messages.
🛠️ Correcciones y aprendizaje / Improvements and Learning
La revisión del código permitió corregir cantidades de ejemplares que no coincidían, impedir carnets y códigos duplicados y validar las entradas numéricas. También se unificó la lectura de datos con getline() para evitar los problemas que aparecían al combinar diferentes formas de entrada sin controlar los caracteres pendientes.
Otra mejora fue sustituir la fecha fija por la fecha del equipo y añadir un historial que permite distinguir entre préstamos activos y devueltos. De esta manera, las operaciones dejan un registro más útil para consultar lo ocurrido durante la sesión.
El proyecto todavía tiene límites. La información permanece en memoria y se pierde al cerrar el programa. Las reservas tampoco tienen vencimiento automático: si la primera persona no retira el material, debe cancelar su turno para dejar avanzar la cola.
Estas limitaciones señalan posibles próximos pasos, como guardar los datos en archivos, incorporar plazos de reserva o mejorar las búsquedas.
Como ejercicio educativo, este programa reúne estructuras, vectores, colas, funciones, condiciones y ciclos dentro de un mismo problema. Su mayor aporte es mostrar cómo cada decisión del código afecta al sistema completo y por qué revisar una solución forma parte del aprendizaje.
Reviewing the code made it possible to correct inconsistent copy counts, prevent duplicate user and material identifiers, and validate numerical input. Data entry was also standardized around getline() to avoid the problems caused by mixing input methods without handling leftover characters.
Another improvement was replacing the fixed date with the computer's date and adding a history view that distinguishes active loans from returned ones. This gives the transactions a more useful record of what happened during the session.
The project still has limitations. Its information stays in memory and is lost when the program closes. Reservations do not expire automatically either: if the first person does not collect the material, they must cancel their reservation to let the queue move forward.
These limitations suggest possible next steps, such as saving data to files, introducing reservation deadlines, or improving searches.
As an educational exercise, this program brings structures, vectors, queues, functions, conditions, and loops together within a single problem. Its greatest contribution is showing how each coding decision affects the entire system and why reviewing a solution is part of learning.
🏆 FICHA DEL PROYECTO / PROJECT STATS 🏆
| 👤 Publicación / Post | |
| 📚 Proyecto / Project | |
| ⌨️ Lenguaje / Language | |
| 🖥️ Interfaz / Interface | |
| 🎯 Enfoque / Focus | |
| 📅 Fecha / Date |