Está en la página 1de 2

Ejercicio Resuelto: MANEJO DE UNA ESTRUCTURA CON ARCHIVO BINARIO

gestionnotas.cpp 1
1 /* Crear un programa en C++ que almacene la información de un estudiante
2 (código, nombres y apellidos, carrera y 5 calificaciones) en una estructura.
3 Aparece inicialmente un menu que presenta las siguientes opciones:
4
5 REGISTRO DE ESTUDIANTES
6
7 1. Agregar un estudiante
8 2. Consultar un estudiante
9 3. Salir
10
11 Su opción [1-3]: _
12
13 Para la opcion 1 debe capturarse desde teclado la información del estudiante,
14 posteriormente se almacena dicha información en un archivo binario.
15 */
16
17 #include <iostream>
18 #include <fstream>
19 using namespace std;
20 #define leeNum(v, m) cout << m, cin >> v, cin.ignore()
21 #define leeText(v, m, t) cout << (m), cin.getline(v, t - 1)
22 #define cancel(m) cout << m, system("pause>nul"), exit(-1)
23
24 struct Estudiante {
25 int codigo;
26 char nombre[30], apellido[30];
27 char carrera[20];
28 float calif[5];
29 };
30
31 void agregaEstud(Estudiante &);
32 short menu();
33
34 int main() {
35 short opc;
36 setlocale(LC_ALL, "");
37 Estudiante alumno;
38
39 do {
40 opc = menu();
41 if (opc == 1)
42 agregaEstud(alumno);
43 if (opc == 2);
44 } while (opc != 3);
45 system("pause>nul");
46 }
47
48 void agregaEstud(Estudiante &alum) {
49 system("cls");
50 fstream datos("BMED-B.dat", ios::in | ios::out | ios::app | ios::binary);
51
52 if (!datos.is_open())
Ejercicio Resuelto: MANEJO DE UNA ESTRUCTURA CON ARCHIVO BINARIO

gestionnotas.cpp 2
53 cancel("Error al abrir el archivo.");
54 cout << "AGREGAR NUEVO ESTUDIANTE\n\n";
55 leeNum(alum.codigo, "Código estudiante: ");
56 leeText(alum.nombre, "Nombres del estudiante: ", 30);
57 leeText(alum.apellido, "Apellidos del estudiante: ", 30);
58 leeText(alum.carrera, "Carrera: ", 20);
59 for (short i = 0; i < 5; i++) {
60 cout << "Nota #" << (i + 1);
61 leeNum(alum.calif[i], ": ");
62 }
63 // Guarda los datos en el archivo binario
64 datos.write((char *)&alum, sizeof(Estudiante));
65 if (datos.fail())
66 cancel("Error al guardar los datos del estudiante.");
67 }
68
69 short menu() {
70 short opcion;
71 do {
72 system("cls");
73 cout << "REGISTRO DE ESTUDIANTES"
74 << "\n1. Agregar un estudiante"
75 << "\n2. Consultar un estudiante" << "\n3. Salir\n\n"
76 << "Digite su opción: ";
77 cin >> opcion;
78 } while (opcion < 1 || opcion > 3);
79 return opcion;
80 }

También podría gustarte