¿Cuándo y dónde usar la instrucción switch en lugar de la instrucción if-else anidada? [cerrado]

-3

Tengo una pregunta con respecto a las estructuras en C++, escribí el siguiente código y quiero asignar a cada estudiante a un curso diferente, he estado tratando de hacer diferentes asignaciones pero no pude encontrar la forma correcta de hacerlo.

Este es mi codigo:

#include <iostream>

using namespace std;

struct Course {
    string CourseCode;
    string CourseName;
    string LecturerName;
    int CourseNumber;
};

struct Student {
    string StudentID;
    string StudentName;
    string Nickname;
    Course info;
};

void menu(void) {
    cout << "=================================" << endl;
    cout << "              MENU              " << endl;
    cout << "=================================" << endl;
    cout << "     1- Add new course" << endl;
    cout << "     2- Display course offered" << endl;
    cout << "     3- Add new students" << endl;
    cout << "     4- Display student list" << endl;
    cout << "     5- Modify student name" << endl;
    cout << "     6- Display student's name after modification" << endl;
    cout << "     7- Exit Program" << endl;
    cout << "=================================" << endl << endl;
}


int main()
{
    Student* ptr[5];
    Student details[5];

    for (int i = 0; i < 2; i++) {
        ptr[i] = &details[i];
    }

    int m, option, stuNo, courNo, n;

    menu();
    cout << "Choose an option from the menu: ";
    cin >> option;

    while (option != 7)
    {
        if (option == 1) {
            cout << "\nHow many courses do you want to enter? [Maximum 2]: ";
            cin >> courNo;
            for (m = 0; m < courNo; m++) {
                cout << "\nEnter course " << m + 1 << " details: " << endl;
                cout << "Course Code: ";
                cin >> ptr[m]->info.CourseCode;
                cout << "Course Name: ";
                cin >> ptr[m]->info.CourseName;
                cout << "Lecturer Name: ";
                cin >> ptr[m]->info.LecturerName;
            }
        }

        else if (option == 2) {
            cout << "\nThe courses details you entered are:" << endl;
            for (m = 0; m < courNo; m++) {
                cout << "\nCourse " << m + 1 << ": " << endl;
                cout << "Course Code: " << ptr[m]->info.CourseCode << endl;
                cout << "Course Name: " << ptr[m]->info.CourseName << endl;
                cout << "Lecturer Name: " << ptr[m]->info.LecturerName << endl;
            }
        }

        else if (option == 3) {
            cout << "\nHow many students do you want to enter? [Maximum 5]: ";
            cin >> stuNo;

            for (m = 0, n=0; m < stuNo; m++, n++) {
                cout << "\nEnter student " << m + 1 << " details: " << endl;
                cout << "ID: ";
                cin >> ptr[m]->StudentID;
                cout << "Name: ";
                cin >> ptr[m]->StudentName;
                cout << "Nickname: ";
                cin >> ptr[m]->Nickname;
                cout << "Course number from the list: ";
                cin >> n; // This gives same output for both students
            }
        }

        else if (option == 4) {
            cout << "\nThe students details you entered are:" << endl;
            for (m = 0; m < stuNo; m++) {
                cout << "\nStudent " << m + 1 << ": " << endl;
                cout << "ID: " << ptr[m]->StudentID << endl;
                cout << "Name: " << ptr[m]->StudentName << endl;
                cout << "Nickname: " << ptr[m]->Nickname << endl;
                cout << "Course " << ptr[n-1]->info.CourseName<< endl;
            }
        }

        else if (option == 5) {
                cout << "\nEnter the student number that has been saved in option 1,2: ";
                cin >> n;
                cout << "\nEnter the new name: ";
                cin >> ptr[n-1]->StudentName;
        }

        else if (option == 6) {
            cout << "\nStudent "<< n <<" new name: ";
            cout << ptr[n - 1]->StudentName;
            cout << endl;
        }

        else
            cout << "Invalid number! Please re-enter a choice from the menu." << endl;

        cout << "=====================================================" << endl;
        cout << "\nChoose an option from the menu: ";
        cin >> option;
    }

    if (option == 7)
        cout << "End of program!" << endl;

}

Sé que el resultado de los cursos asignados a los estudiantes será el mismo en función de mi código, ya que solo tengo n, cómo cambiarlo para que sea diferente para cada estudiante

Esta es la salida:

=================================
              MENU
=================================
     1- Add new course
     2- Display course offered
     3- Add new students
     4- Display student list
     5- Modify student name
     6- Display student's name after modification
     7- Exit Program
=================================

Choose an option from the menu: 1

How many courses do you want to enter? [Maximum 2]: 2

Enter course 1 details:
Course Code: 111
Course Name: co1
Lecturer Name: lect1

Enter course 2 details:
Course Code: 222
Course Name: co2
Lecturer Name: lect2
=====================================================

Choose an option from the menu: 3

How many students do you want to enter? [Maximum 5]: 2

Enter student 1 details:
ID: 1111
Name: student1
Nickname: stud1
Course number from the list: 2

Enter student 2 details:
ID: 2222
Name: student2
Nickname: stud2
Course number from the list: 1
=====================================================

Choose an option from the menu: 4

The students details you entered are:

Student 1:
ID: 1111
Name: student1
Nickname: stud1
Course co2

Student 2:
ID: 2222
Name: student2
Nickname: stud2
Course co2
=====================================================

Choose an option from the menu: 7
End of program!
1
  • Este es un escenario extremadamente "artificial". Sin embargo, hay dos problemas desde el principio: 1) Desea ingresar "Estudiantes" y "Cursos" POR SEPARADO . Almacene cada uno en matrices de variables separadas. 2) Cuando llega el momento de asignar "cursos" a "estudiantes", debe realizar un seguimiento de los cursos que ya se asignaron (a un estudiante diferente). ¿Quizás otra variable (lastCourseAssigned)? TAMBIÉN: Quiere asegurarse de que si asigna espacio para 5 estudiantes ... imprime un "error" si el usuario intenta ingresar más de 5.
    paulsm4
    14 oct a las 0:20
1

El problema es que está almacenando la lista de correos Courseelectrónicos disponibles Studenten la misma lista. Debe tener una lista separada para Courses y Students, y luego hacer que las dos listas hagan referencias cruzadas entre sí según sea necesario.

Por ejemplo, cambie el Course info;miembro de Studenta en su std::string CourseCode;lugar, y luego podrá buscarlo CourseCodeen la Courselista s cuando sea necesario.

Prueba algo más parecido a esto:

#include <iostream>
#include <string>
#include <limits>
using namespace std;

struct Course {
    string CourseCode;
    string CourseName;
    string LecturerName;
    int CourseNumber; // <-- what is this for???
};

struct Student {
    string StudentID;
    string StudentName;
    string Nickname;
    string CourseCode;
};

void menu() {
    cout << "=================================" << endl;
    cout << "              MENU              " << endl;
    cout << "=================================" << endl;
    cout << "     1- Add new course" << endl;
    cout << "     2- Display course offered" << endl;
    cout << "     3- Add new students" << endl;
    cout << "     4- Display student list" << endl;
    cout << "     5- Modify student name" << endl;
    cout << "     6- Display student's name after modification" << endl;
    cout << "     7- Exit Program" << endl;
    cout << "=================================" << endl << endl;
}

string getCourseName(const string &CourseCode, const Course *courses, int courNo) {
    for(int m = 0; m < courNo; ++m) {
        if (courses[m].CourseCode == CourseCode)
            return courses[m].CourseName;
    }
    return "";
}

int main()
{
    Student students[5];
    Course courses[2];

    int n, m, option, stuNo = 0, courNo = 0, modNo = 0;

    menu();

    do
    {
        cout << "Choose an option from the menu: ";
        cin >> option;

        switch (option) {
            case 1:
                if (courNo >= 2) {
                    cout << "\nCourse list is full";
                    break;
                }

                cout << "\nHow many courses do you want to enter? [Maximum " << 2 - courNo << "]: ";
                cin >> n;

                for (m = 0; m < n; ++m) {
                    cout << "\nEnter course " << m + 1 << " details: " << endl;
                    cout << "Course Code: ";
                    cin >> courses[courNo].CourseCode;
                    cout << "Course Name: ";
                    cin >> courses[courNo].CourseName;
                    cout << "Lecturer Name: ";
                    cin >> courses[courNo].LecturerName;
                    ++courNo;
                }

                break;

            case 2:
                cout << "\nThe courses details you entered are:" << endl;
                for (m = 0; m < courNo; ++m) {
                    cout << "\nCourse " << m + 1 << ": " << endl;
                    cout << "Course Code: " << courses[m].CourseCode << endl;
                    cout << "Course Name: " << courses[m].CourseName << endl;
                    cout << "Lecturer Name: " << courses[m].LecturerName << endl;
                }
                break;

            case 3:
                if (stuNo >= 5) {
                    cout << "\nStudent list is full";
                    break;
                }

                cout << "\nHow many students do you want to enter? [Maximum " << 5 - stuNo << "]: ";
                cin >> n;

                for (m = 0; m < n; ++m) {
                    cout << "\nEnter student " << m + 1 << " details: " << endl;
                    cout << "ID: ";
                    cin >> students[stuNo].StudentID;
                    cout << "Name: ";
                    cin >> students[stuNo].StudentName;
                    cout << "Nickname: ";
                    cin >> students[stuNo].Nickname;
                    cout << "Course number from the list: ";
                    cin >> students[stuNo].CourseCode;
                    ++stuNo;
                }

                break;

            case 4:
                cout << "\nThe students details you entered are:" << endl;
                for (m = 0; m < stuNo; ++m) {
                    cout << "\nStudent " << m + 1 << ": " << endl;
                    cout << "ID: " << students[m].StudentID << endl;
                    cout << "Name: " << students[m].StudentName << endl;
                    cout << "Nickname: " << students[m].Nickname << endl;
                    cout << "Course: " << students[m].CourseCode << " " <<  getCourseName(students[m].CourseCode, courses, courNo) << endl;
                }
                break;

            case 5:
                cout << "\nEnter the student number that has been saved in option 1,2: ";
                cin >> n;

                if (n < 1 || n > stuNo) {
                    cout << "\nInvalid student number";
                    break;
                }

                cout << "\nEnter the new name: ";
                cin >> students[n-1].StudentName;

                modNo = n;
                break;

            case 6:
                if (modNo < 1 || modNo > stuNo) {
                     cout << "\nNo student modified";
                     break;
                }

                cout << "\nStudent " << modNo << " new name: ";
                cout << students[modNo-1].StudentName << endl;
                modNo = 0;

                break;

            case 7:
                break;

            default:
                cout << "Invalid number! Please re-enter a choice from the menu." << endl;
                break;
        }

        cout << "=====================================================" << endl;
    }
    while (option != 7);

    cout << "End of program!" << endl;
}
0