Guardar datos de alumnos de una escuela ¡Practicando con AzulSchool! [ESP-ENG] | C++

in Develop Spanish2 years ago

¿Qué tal todo? Por acá estoy de vuelta con más programación, de la mano del curso gratuito de AzulSchool sobre C++. La meta sigue siendo terminarlo antes del 29 de este mes. Ya vamos por el 69%, la idea era hacer más proyectos esta semana pero el trabajo ha exigido más y aparte de ello subestimé este último, por las validaciones me tomó más tiempo del esperado.

Para esta ocasión decidí hacer declaraciones globales de las variables centrales, pues me evitaba varios problemas al sincronizar los arreglos. Comenzamos con "char name[20][40]" que es un arreglo de 20 variables de tipo char con 40 caracteres cada uno (contando al nulo), este arreglo almacena los nombres de los estudiantes. Posteriormente están 5 arreglos con nombre base "subject" que se encargan de almacenar las notas de cada una de las cinco materias, respectivamente. Luego aparece "char n_Subject[5][40]" que guarda los nombres de cada materia, ejemplo: Matemáticas, Castellano, Inglés Técnico, Programación, Física. Para esta parte tuve un pequeño dilema porque parte del enunciado pide que los datos puedan modificarse, por "datos" solo incluí las notas ya registrada, pero después reflexionaba en que también debí haber incluído los nombres de las materias y los nombres de los alumnos. Por ahora no lo añadiré, pues el principio es el mismo que en el modificar las notas solo que cambiando la función de validación. Además de que ya me queda poco tiempo, así que debo administrarlo bien para lograr la gran meta.

Entre las funciones están "To_String" que recibe un entero y devuelve un string, ej: int i = 1 -> Retorna "1". Luego "IsNInt_Array", que sirve para apoyar en la validación de los arreglos para saber si son números enteros o no. "name_Validator" sirve para validar los nombres, recibe un arreglo de char y un contador para identificar cuál es la posición del arreglo que se desea verificar. Sigue "name_colecter" que se encarga de recopilar los nombres en el arreglo "names", luego de haberlos verificado. "Show_Students" se encarga de mostrar los estudiantes registrados hasta el momento, su promedio, la materia en las que le va mejor y en las que le va peor, para ello también se apoya en otra función que es "Show_Subject" que es un selector que devuelve el nombre de la materia y su nota, dependiendo de que número reciba por parámetro, esto para el apartado de mejor y peor nota del estudiante. "Validator_N" se encarga de validar con detalle los número para los arreglos, apoyándose en la función "isNInt_Array" y también en un rango que va desde "min" a "max", definido por sus parámetros, también recibe un mensaje y una variable booleana que se llama "Tsubject_FstudentOrNsubject" que por su nombre explica que de ser True se trata de validar una nota de una materia, por otro lado, de ser False es el ID de un estudiante o el N# de una materia lo que se desea validar, esto lo hice para que la multifuncionalidad fuese posible y así no tener tanta redundancia en el código. También tiene un arreglo de tipo char llamado "copy_array" que es el que recibirá el número validado.

Sigue "subject_selector" que a diferencia de "Show_Subject", se encarga de copiar el arreglo que reciba por parámetro a alguno de los arreglos de notas, según sea el contador recibido, el ID de estudiante y el arreglo tipo char con la nota. "Notes_Colect" se encarga de la recolección de notas para cada arreglo, apoyándose en los validadores ya mencionados y también en el selector, su parámetro es un booleano llamado "mod_request" porque también está pensada para ser multifuncional. Si el booleano que recibe es "True", entonces se adapta para la función "Modificar datos del estudiante", si por otro lado es "False", se encarga del registro de 0, de un estudiante. Ya casi al final está "Subject_Name_Colect" que se encarga de recoger los nombres de las 5 materias que se trabajarán en los registros; por acá tuve otro dilema porque pensaba que los estudiantes podrían estar cursando materias diferentes, pero eso no me pareció muy consistente para este programa de práctica, así que a todos se les asigna las mismas materias como en el bachillerato por acá en Venezuela. Se puede hacer un poco más universitario pero considero que en ese caso estaría mejor un sistema con interfaz gráfica más agradable y que incluso pueda ser útil a futuro, por el trabajo que llevaría perfeccionarlo. La función "interfaz_Colect" seguro la recuerdan por los proyectos anteriores, esta solo se encarga de mostrar un mensaje por pantalla con el requerimiento específico que se coloca por su parámetro de tipo string. Finalmente está el "menu" que interactúa con el usuario para mostrarle las opciones posibles que tiene con este pequeño gestor de notas y promedios de estudiantes.

Un detalle que encontré fue que "bool isNInt_Array()" retorna false CADA VEZ QUE ENCUENTRA UN CARACTER NO NUMÉRICO, por lo que el mensaje de error aparece varias veces. Eso es mejorable, mi falla fue que reciclé esta función de mis tiempos en Programación Orientada a Objetos en la universidad, en concreto de un parcial en el que varios compañeros compartimos un recopilatorio de funciones clave para poder terminar a tiempo, dado que se permitía tener una plantilla antes de empezar, según recuerdo. "name_Validator" también forma parte de esos tiempos, tan solo modifiqué algunos detalles para esta ocasión.

How's it going? I'm back with more programming, thanks to AzulSchool's free C++ course. The goal is still to finish it before the 29th of this month. We are already at 69%, the idea was to do more projects this week but the work has demanded more and apart from that I underestimated this last one, because of the validations it took me more time than expected.

For this occasion I decided to make global declarations of the central variables, because it avoided me several problems when synchronizing the arrays. We start with "char name[20][40]" which is an array of 20 char variables with 40 characters each (counting the null), this array stores the names of the students. Subsequently there are 5 arrays with base name "subject" that are in charge of storing the grades of each of the five subjects, respectively. Then appears "char n_Subject[5][40]" that stores the names of each subject, example: Mathematics, Spanish, Technical English, Programming, Physics. For this part I had a small dilemma because part of the statement asks that the data can be modified, for "data" I only included the grades already registered, but later I reflected that I should have also included the names of the subjects and the names of the students. I will not add it for now, because the principle is the same as in modifying the grades, only changing the validation function. Besides, I don't have much time left, so I must manage it well to achieve the big goal.

Among the functions are "To_String" that receives an integer and returns a string, ex: int i = 1 -> Returns "1". Then "IsNInt_Array", which is used to support in validating arrays to know if they are integers or not. "name_Validator" is used to validate the names, it receives a char array and a counter to identify which array position to verify. It is followed by "name_collector" which is in charge of collecting the names in the "names" array, after having verified them. "Show_Students" is in charge of showing the students registered so far, their average, the subject in which they do better and in which they do worse, for this it also relies on another function that is "Show_Subject" which is a selector that returns the name of the subject and its grade, depending on the number received by parameter, this for the best and worst grade section of the student. "Validator_N" is in charge of validating in detail the numbers for the arrays, relying on the function "isNInt_Array" and also on a range that goes from "min" to "max", defined by its parameters, it also receives a message and a boolean variable called "Tsubject_FstudentOrNsubject" that by its name explains that if it is True it is validating a grade of a subject, on the other hand, if it is False it is the ID of a student or the N# of a subject that you want to validate, I did this so that the multifunctionality was possible and thus not to have so much redundancy in the code. It also has a char array called "copy_array" which is the one that will receive the validated number.

It is followed by "subject_selector" which, unlike "Show_Subject", is in charge of copying the array received by parameter to one of the note arrays, depending on the counter received, the student ID and the char array with the note. "Notes_Collect" is in charge of collecting notes for each array, relying on the validators already mentioned and also on the selector, its parameter is a boolean called "mod_request" because it is also intended to be multifunctional. If the boolean it receives is "True", then it is adapted for the function "Modify student data", if on the other hand it is "False", it is in charge of the registration of 0, of a student. Almost at the end is "Subject_Name_Collect" that is in charge of collecting the names of the 5 subjects that will be worked in the records; here I had another dilemma because I thought that the students could be taking different subjects, but that did not seem to me very consistent for this practice program, so all are assigned the same subjects as in the high school here in Venezuela. It is possible to make it a little more university-like, but I consider that in that case it would be better to have a system with a more pleasant graphical interface and that it could even be useful in the future, because of the work that it would take to perfect it. The function "interface_Colect" surely you remember it for the previous projects, this one is only in charge of showing a message by screen with the specific requirement that is placed by its parameter of type string. Finally there is the "menu" that interacts with the user to show him the possible options that he has with this small manager of grades and averages of students.

One detail I found was that "bool isNInt_Array()" returns false EVERY TIME IT FINDS A NON-NUMERIC CHARACTER, so the error message appears several times. That's improvable, my fault was that I recycled this function from my time in Object Oriented Programming in college, specifically from a partial in which several classmates shared a compilation of key functions to be able to finish on time, since it was allowed to have a template before starting, as I remember. "name_Validator" is also part of those times, I just modified some details for this occasion.


Portada post programacion, tech.png
Edited with CANVA

Programación c++.png

image.png
From AzulSchool, by: Angel Sánchez

image.png

image.png

image.png

Programación c++.png

El recolector de nombres se basa en un bucle que solo se cierra si el validador da luz verde al nombre ingresado. También valida que no se registren más de 20 nombres. No aumenta el contador de estudiantes que está entre las variables globales porque ese aumento ya se hace al registrar las 5 notas, por lo que habría un error si se aumentase de nuevo acá. La función "Show_Subject" ya fue explicada arriba, sin embargo puedo agregar que con una estructura mucho de este código se resume, pues ya no hay tanta individualidad entre los arreglos, sino que se reúne todo en una "plantilla" por así decirlo. Luego entra en acción "Show_Students", que expliqué un poco antes, pero que vale la pena detallar. Tiene una variable de tipo float "general_Av" para el promedio general y cuatro de tipo int (aux1,aux2, mayorr y menor). La primera ya por el nombre delata su utilidad, el resto son para el cálculo de que materia es la que lleva con mejor y peor nota, a través de una serie de if, que siguen el mismo principio que en el proyecto de temática parecida que traje antes, llamado "Listado de notas y un poco más", contando también con la deficiencia de que si se repite una nota de las mejores, entonces solo se mostrará una de ellas, al igual con las menores. La función stof fue punta de lanza para el cálculo de ambos promedios, que parten de la fórmula que dice que un promedio se calcula como la sumatoria de los elementos entre el número (conteo/cantidad) de los mismos. Tiene un pequeño if-else antes de finalizar que dice que en caso de que solo se haya registrado un estudiante pues no se debe hacer la división (sería entre 1, es decir innecesaria).

"Validator_N" también la expliqué un poco al comienzo, pero me apetece dar más detalles. La primera variable es un arreglo de tipo char que guarda la nota validadda y la segunda es un booleano llamado "flag/bandera" que sirve de parámetro para el bucle. Se comienza llamando a la interfaz para informar al usuario, luego verificando el booleano del parámetro para saber si quiere recolectar una nota de una materia, un ID de estudiante o un N# de materia. Esto solo varía respecto al mensaje que se mostrará, en un caso se muestra el nombre de la materia cuya nota se quiere registrar y en el otro se muestran los estudiantes con el nombre de sus materias y sus respectivas notas registradas hasta el momento. Luego se valida el arreglo, primero se consulta si es numérico y luego si está en el rango establecido por min-max en los parámetros y finalmente se copia el contenido validado de note al arreglo recibido por parámetro llamado "copy_array".

The name collector is based on a loop that only closes if the validator gives the green light to the name entered. It also validates that no more than 20 names are registered. It does not increment the student counter that is among the global variables because that increment is already done when registering the 5 grades, so there would be an error if it was incremented again here. The function "Show_Subject" was already explained above, however I can add that with a structure much of this code is summarized, because there is no longer so much individuality between the arrangements, but it all comes together in a "template" so to speak. Then "Show_Students" comes into action, which I explained a bit earlier, but is worth detailing. It has a variable of type float "general_Av" for the general average and four of type int (aux1,aux2, majorr and minor). The first one already by the name gives away its usefulness, the rest are for the calculation of which subject is the one with the best and worst grade, through a series of if, which follow the same principle as in the project of similar subject that I brought before, called "List of grades and a little more" , having also the shortcoming that if a top note is repeated, then only one of them will be displayed, as well as the lower ones. The stof function was the spearhead for the calculation of both averages, which start from the formula that says that an average is calculated as the sum of the elements between the number (count/quantity) of them. It has a small if-else before the end that says that in case only one student has registered, the division should not be done (it would be by 1, i.e. unnecessary).

"Validator_N" I also explained it a bit at the beginning, but I feel like giving more details. The first variable is a char array that stores the validated note and the second is a boolean called "flag/flag" that serves as a parameter for the loop. You start by calling the interface to inform the user, then checking the boolean of the parameter to know if you want to collect a grade for a subject, a student ID or a subject N#. This only varies with respect to the message that will be displayed, in one case the name of the subject whose grade is to be recorded is displayed and in the other the students are displayed with the name of their subjects and their respective grades recorded so far. Then the array is validated, first it is consulted if it is numeric and then if it is in the range established by min-max in the parameters and finally the validated content of note is copied to the array received by parameter called "copy_array".

Programación c++.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

No tengo nada para agregar respecto a "subject_selector", pero si para "Notes_Colect" que en caso de que no se pida la modificación de alguno de los datos ya registrados, entra en un bucle que da 5 vueltas (para las cinco notas 0-4), apoyándose en "Validator_N" y "subject_selector", limpia el buffer y al terminar aumenta el contador de estudiantes (variable global).

En caso de que si se pida una modificación (mod_request==true), ya no hay bucle de cinco vueltas sino que se pide el numero asociado al estudiante cuya nota se quiera cambiar (ID, 1-20), luego se pide el número asociado a la materia (1-5) y luego el asociado a la nota (0-10). Posteriormete estos datos recopilados reemplazan los viejos con la función "subject_selector", restando 1 al parámetro del número de materia y 1 al parámetro del número de estudiante porque ambos conteos empiezan en 0.

Sigue la función que recopila los nombres de las materias y honestamente, podría haber hecho multifuncional la función que recopila los nombres y así ahorrar código pero no se me ocurrió para ese apartado. Ambas funciones son muy parecidas, cambian por el bucle de 5 vueltas (para los cinco nombres) y que estos se muestran una vez el registro culmina.

Finalmente la función "menú", que no es más que la interfaz principal para que el usuario interactúe con las opciones disponibles. Hay un par de validaciones, una para evitar que se trate de modificar si no hay estudiantes registrados y otra para que se llame a la función para registrar las 5 materias si es la primera vez que se intenta agregar un estudiante. El resto no es más que una copia de mis anteriores menús, pues por lo general los reciclo. He pensado en hacer un modelo un poco diferente pero por ahora lo dejaré como una posibilidad a futuro.

I have nothing to add regarding "subject_selector", but for "Notes_Colect" that in case a modification of any of the already registered data is not requested, it enters in a loop that goes around 5 times (for the five notes 0-4), relying on "Validator_N" and "subject_selector", clears the buffer and at the end increases the student counter (global variable).

If a modification is requested (mod_request==true), there is no longer a five-turn loop, but the number associated with the student whose grade is to be changed (ID, 1-20) is requested, then the number associated with the subject (1-5) and then the number associated with the grade (0-10). These collected data then replace the old ones with the function "subject_selector", subtracting 1 from the subject number parameter and 1 from the student number parameter because both counts start at 0.

The function that collects the subject names follows and honestly, I could have made the function that collects the names multifunctional and thus saved code but it didn't occur to me for that section. Both functions are very similar, they change because of the 5-turn loop (for the five names) and that these are displayed once the record completes.

Finally the "menu" function, which is just the main interface for the user to interact with the available options. There are a couple of validations, one to avoid trying to modify if there are no students registered and another to call the function to register the 5 subjects if it is the first time you try to add a student. The rest is nothing more than a copy of my previous menus, as I usually recycle them. I have thought about making a slightly different model but for now I will leave it as a possibility for the future.

Programación c++.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

Gif proyecto 5.gif

Programación c++.png

¡Y bueno... Eso es todo por hoy! Este proyecto fue bastante largo, diría que de los más largos que he traído, definitivamente fue una buena práctica. Ya van 5/9 ¿Crees que podré terminar a tiempo? Yo me siento optimista, pero veamos que permite el Señor.

And well... That's all for today! This project was quite long, I'd say one of the longest I've ever brought, it was definitely good practice. That's 5/9 already, do you think I'll be able to finish on time? I'm feeling optimistic, but let's see what the Lord allows.

Programación c++.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)

Sort:  


The rewards earned on this comment will go directly to the people( @gabrielrr17 ) sharing the post on Twitter as long as they are registered with @poshtoken. Sign up at https://hiveposh.com.

¡Felicitaciones!



Estás participando para optar a la mención especial de nuestra COMUNIDAD (Recompensa de 1 Hive), también has recibido 1 ENTROKEN.

1. Invierte en el PROYECTO ENTROPÍA y recibe ganancias semanalmente. Entra aquí para más información.

2. Contáctanos en Discord: https://discord.gg/hkCjFeb

3. Suscríbete a nuestra COMUNIDAD, apoya al trail de @Entropia y así podrás ganar recompensas de curación de forma automática. Entra aquí para más información sobre nuestro trail.

4. Creación de cuentas nuevas de Hive aquí.

5. Visita nuestro canal de Youtube.

Atentamente

El equipo de curación del PROYECTO ENTROPÍA

¡Gracias por el apoyo @entropia!

Congratulations @gabrielr29! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You published more than 300 posts.
Your next target is to reach 350 posts.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out the last post from @hivebuzz:

Balls of Steel - HiveFest⁷ Petanque Tournament Results
Support the HiveBuzz project. Vote for our proposal!