¡Saludos! Por acá vuelvo con algo de programación, esta vez con más de AzulSchool, en concreto, del curso hecho por don Ángel Sánchez que estoy decidido a acabar. De hecho debo hacerlo pronto, pues se acerca el inicio de semestre y el tiempo disponible será mucho menor. En concreto llevo un 35% así que considero que voy a buen ritmo, si sigo como voy debería estar listo antes de terminar el mes o quizás poco después.
Pero bueno, ya entrando en materia, el programa solicitado corresponde al proyecto 1 del curso. Este "traductor de fecha" deberá recibir un día, mes y año por teclado, en formato numérico. Para luego mostrarlo en estos posibles formatos:
- Mes completo, día y año
- Mes abreviado (3 letras, ejemplo: Oct) , día y año
- Clásico (dd/mm/yy)
Ya el último formato estaría al 80% listo si consideramos como ingresa el usuario los datos. Tan solo habría que añadir los "slash" (/). Así que esa sería la opción más sencilla a trabajar.
En las librerías me apoyé de las mismas que en el último post, solo que en esta ocasión organicé un poco más las cosas para que el main no tuviese mucho código y las funciones estuviesen declaradas arriba y desarrolladas abajo. Como parte de un sabia corrección de don @shadowmyst. Cosa que los profesores me habían mencionado antes pero lo cierto es que las malas costumbres se arraigan fácil, así que seguro me tome tiempo adaptarme bien al este orden, pero vaya, hay que dar el paso.
Luego comencé desarrollando las funciones que incluyen las opciones de string de cada mes, que serán retornadas según el entero que se envíe como parámetro (1-Enero, 2-Febrero, 3-Marzo...). Por otro lado la segunda, "options_ii", es una gemela que solo se distingue por entregar los meses abreviados.
Greetings! Here I come back with some programming, this time with more from AzulSchool, specifically, from the course made by Mr. Angel Sanchez that I am determined to finish. In fact I must do it soon, since the beginning of the semester is approaching and the time available will be much less. I'm about 35% complete, so I consider that I'm going at a good pace, if I continue as I'm going I should be ready before the end of the month or maybe a little later.
But well, now getting into the subject, the requested program corresponds to project 1 of the course. This "date translator" should receive a day, month and year by keyboard, in numerical format. To then display it in these possible formats:
- Full month, day and year
- Abbreviated month (3 letters, example: Oct) , day and year
- Classic (dd/mm/yy)
The last format would be 80% ready if we consider how the user enters the data. We would only have to add the "slash" (/). So that would be the simplest option to work with.
In the libraries I used the same as in the last post, only this time I organized things a little more so that the main did not have much code and the functions were declared at the top and developed below. As part of a wise correction of don @shadowmyst. Something that the teachers had mentioned to me before but the truth is that bad habits take root easily, so it sure took me time to adapt well to this order, but wow, you have to take the step.
Then I started developing the functions that include the string options for each month, which will be returned according to the integer sent as parameter (1-January, 2-February, 3-March...). On the other hand the second one, "options_ii", is a twin that only differs by delivering the abbreviated months.
Para las siguientes funciones nos encontramos con "filtros"/"validadores", que se encargan de evitar que la fecha quede como "Oncembre, 55 -501". Aunque no cubren años bisiestos ni la diferencia 30-31 de algunos meses. La validación no fue solicitada pero decidí incluirla para repasar mejor y seguir poniéndome a prueba.
La primera se encarga del día, "validator_day" cuenta con una variable de tipo char con dos espacios (0-1) para cubrir los dos caracteres máximos que tiene ese campo. La segunda variable corresponde a la que será retornada, es decir el día ya validado. El proceso está desarrollado en un bucle do-while que pide el dato, lo pasa por un if-else que incluye un intervalo de (1-31) de los que pueden ser aceptados. Y la condición del while viene a ser la misma.
De no cumplirse, se envía un mensaje de error en pantalla con "cerr". Si todo sale bien se asigna el valor filtrado a la variable que será retornada "dd_validated" y luego se limpia el buffer con cin.clear() para evitar errores de saturación, esas clásicas "explosiones del programa". Las otras dos funciones de validación son de hecho parientes muy cercanas pues cumplen el mismo fin con una estructura bastante similar. Tan solo se distinguen por los intervalos de sus condiciones filtro, adaptadas para el mes y el año.
Se encontrará "atoi" varias veces porque es necesario convertir los valores de tipo char a int para que funcionen bien como intervalo en las condiciones del if-else y el while.
For the following functions we find "filters"/"validators", which take care of avoiding that the date is left as "Oncembre, 55 -501". Although they do not cover leap years or the 30-31 difference of some months. Validation was not requested but I decided to include it to review better and keep testing myself.
The first one is in charge of the day, "validator_day" has a variable of type char with two spaces (0-1) to cover the two maximum characters that this field has. The second variable corresponds to the one that will be returned, i.e. the day already validated. The process is developed in a do-while loop that asks for the data, passes it through an if-else that includes an interval of (1-31) of those that can be accepted. And the while condition is the same.
If it is not fulfilled, an error message is sent on screen with "cerr". If all goes well, the filtered value is assigned to the variable that will be returned "dd_validated" and then the buffer is cleared with cin.clear() to avoid saturation errors, those classic "program explosions". The other two validation functions are in fact very close relatives as they serve the same purpose with a quite similar structure. They differ only in the intervals of their filter conditions, adapted for month and year.
You will encounter "atoi" several times because it is necessary to convert the char values to int in order to make them work well as intervals in the if-else and while conditions.
Llegamos al núcleo del programa, la función "translate", que se encarga de llamar a los validadores, a los retornadores y de organizar los posibles formatos a mostrar en pantalla. Esta tiene un único parámetro que se asocia al switch interno, de tal manera que el caso 1 es para el formato de Mes completo, el caso 2 para mes abreviado y el caso 3 para el clásico (dd/mm/yy). Luego entonces se incluyen espacios y saltos de línea para mejorar la estética y se coloca el mensaje de error como default en caso de que se escoja una opción no registrada.
En concreto, el mensaje con la fecha en nuevo formato se forma al asignarlo a una variable string, llamando al retornador "options_i" u "options_ii" (solo en caso 1 o 2), luego añadiendo el día y año filtrados y separándolos por espacios y comas. Esta función queda "aninada" a la función principal que corresponde al menú de inicio y que es la única función llamada en el main, "translate_menu", esta muestra una portada al igual que "translate", solo que el mensaje no está enfocado a la recolección del día, mes y año, sino a que el usuario elija el formato que desea para su fecha. Luego se llama a la ya mencionada función translate, enviando como parámetro la variable de control del switch, que viene a ser reciclada, de tal manera que se ahorran recursos. Se incluyen pausas y limpiezas de pantalla para mejorar la estética, además de un mensaje de despedida en caso de que se quiera "Salir". Se puede observar el programa en funcionamiento justo debajo en un gif, de tal manera que se aprecie a detalle el proceso de interacción usuario-consola.
We come to the core of the program, the "translate" function, which is in charge of calling the validators, the returners and organizing the possible formats to be displayed on the screen. It has a single parameter that is associated with the internal switch, so that case 1 is for the full month format, case 2 for the abbreviated month and case 3 for the classic (dd/mm/yy). Then spaces and line breaks are included to improve aesthetics and the error message is set as default in case an unregistered option is chosen.
Specifically, the message with the date in new format is formed by assigning it to a string variable, calling the "options_i" or "options_ii" returner (only in case 1 or 2), then adding the filtered day and year and separating them by spaces and commas. This function is "nested" to the main function that corresponds to the start menu and that is the only function called in the main, "translate_menu", this shows a cover just like "translate", only that the message is not focused on the collection of the day, month and year, but for the user to choose the format you want for your date. Then the aforementioned translate function is called, sending as parameter the control variable of the switch, which is recycled, thus saving resources. Pauses and screen wipes are included to improve the aesthetics, as well as a goodbye message in case you want to "Exit". You can see the program in operation just below in a gif, so that the user-console interaction process can be appreciated in detail.
¡Y bueno... Eso es todo por hoy! Te recomiendo que pases por el curso de AzulSchool si deseas seguir creciendo en este grandioso mundo de la programación. También puedes encontrar apoyo en Youtube con canales como "pildoras informáticas", "Programación ATS" (Que en paz descanse Alejandro Taboada) y también con tu teléfono usando la aplicación MIMO.
And well... That's all for today! I recommend you to go through the AzulSchool course if you want to continue growing in this great world of programming. You can also find support on Youtube with channels like "pildoras informáticas", "Programación ATS" (May Alejandro Taboada rest in peace) and also with your phone using the MIMO application.
Puedes encontrar el curso gratuito en el que aparece el enunciado original en AzulSchool. En el módulo del proyecto 1
You can find the free course in which the original statement appears at AzulSchool. In the module of the project 1