另一个struct内部的结构数组的成员变量不会被引用

时间:2016-05-31 22:07:56

标签: c++ arrays struct

这真的让我陷入了困境。

我有两个结构,员工和部门。在部门结构中,是一组雇员结构。

当我调用将员工添加到部门(add_empl_to_dept())的函数时,值会正确保存到部门的员工数组(empl_in_dept []),但仅限于函数范围内。程序返回main后,值将丢失。

为什么会发生这种情况?如果能解决这个问题怎么办?

对于这里疯狂的代码长度感到抱歉。复制/粘贴整个内容比分开它更容易。如果这是一个问题,请告诉我。

感谢您的帮助!!!

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

struct employee
{
    int eID;// stores the employee ID number
    char fName[40]; //stores the employee's first 
    char lName[40];//stores the employee's last name
    float salary;//stores the employee's salary

};

// structure for storing department information
struct department
{
    int dID;//stores the department's ID number
    char dName[40];//stores the name of the department
    int empl_in_dept_count;// stores how many employees have been added to the department
    employee empl_in_dept[10];//stores upto 10 employees

};    

bool dCheck(department dList[], int dCount, int dID);
bool eCheck(employee eList[], int eCount, int eID);
bool empl_in_dept_check(department dList[], int dCount, employee eList[], int eID, int dID);
void addDepartment(department dList[], int &dCount);
void addEmployee(employee eList[], int &eCount);
void add_empl_to_dept(department dList[], int dCount, employee eList[], int eCount);
void ePrint(employee eList[], int eCount);
void dPrint(department dList[], int dCount, employee eList[]);
void e_in_dPrint(department dList[], int dCount, employee eList[]);
void average(department dList[], int dCount, employee eList[]);
void save(department dList[], int dCount, employee eList[], int eCount);
void load(department dList [], int &dCount, employee eList[], int &eCount);
void printMenu();

int main()
{
    employee eList[30];//stores individual employee information in each index 
    int eCount = 0; //stores total number of employees added. Used as an index number for the eList array when adding employees
    department dList[10];//stores the individual department information in each index.
    int dCount = 0; //stores total number of departments added. Used as an index number for the dList array when adding departments

//initialize all dList's empl_in_dept_count variables to zero
for (int i = 0; i < 10; i++)
{
    dList[i].empl_in_dept_count = 0;

}

//do-while loop based on the bool variable, run. When run = false, the program ends. 
do
{
    printMenu();//prints out the menu and prompts the user for a choice.

    do// check for a valid menu choice
    {
        cin >> menu;//reads in the user's menu choice

        cout << "----------------------------------------------------------" << endl;
        if (menu <1 || menu > 10)
        {
            cout << "That is not a valid selection." << endl;
            printMenu();//prints out the menu and prompts the user for a choice.
        }

    }while(menu <1 || menu > 10);

    //switch statement based on the variable, menu. 
    switch(menu)
    {
        case 1://calls the addDepartment function
            addDepartment(dList, dCount); 
            break;
        case 2://calls the addEmployee function
            addEmployee(eList, eCount);
            break;
        case 3://calls the add_empl_to_dept function
            add_empl_to_dept(dList, dCount, eList, eCount);
            break;
        case 4://calls the ePrint function
            ePrint(eList, eCount);
            break;
        case 5://calls the dPrint function
            dPrint(dList, dCount, eList);
            break;
        case 6://calls the e_in_dPrint function
            e_in_dPrint(dList, dCount,eList);
            break;
        case 7://calls the average function
            average(dList, dCount, eList);
            break;
        case 8://calls the save function
             save(dList, dCount, eList, eCount);
            break;
        case 9://calls the load function
            load(dList, dCount, eList, eCount);
            break;
        case 10://sets run to false and ends the program
            run = false;
            break;  
    }
}while(run);

return 0;

}

/*
    ============================================================================
Function : dCheck
Parameters : department dList, int dCount, and int dID
Return : True or false depending on if a department exists
Description : This function checks a user entered department ID against the dList arrays previously 
entered dIDs to see if the ID number has already been entered. 
============================================================================
*/
bool dCheck(department dList[], int dCount, int dID)
{
    //Cycles through the dList array to compaire the user entered dID number to the dList.dID number
    for(int i = 0; i <= dCount; i++)
    {
        if (dList[i].dID != dID && i == dCount)//If there is no match, the function returns false
        {
            return false;
        }
        if(dList[i].dID == dID)//If there is a match, the function returns true
        {
            return true;
        }
    }
}

/*
============================================================================
Function : eCheck
Parameters : employee eList, int eCount, and int dID
Return : True or false depending on if a employee exists
Description : This function checks a user entered employee ID against the eList arrays previously 
entered eIDs to see if the ID number has already been entered. 
============================================================================
*/
bool eCheck(employee eList[], int eCount, int eID)
{
    //Cycles through the eList array to compaire the user entered eID number to the eList.eID number
    for(int i = 0; i <= eCount; i++)
    {
        if (eList[i].eID != eID && i == eCount)//If there is no match, the function returns false
        {
            return false;
        }
        if(eList[i].eID == eID)//If there is a match, the function returns true
        {
            return true;
        }
    }
}

/*
============================================================================
Function : empl_in_dept_check
Parameters : department dList, int dCount, employee eList, int eID, int dID
Return : True or false depending on if a employee exists in a department
Description : This function checks a user entered employee ID against the dList arrays previously 
entered eIDs to see if the ID number has already been entered into the department. This function assumes
that the dCheck and dCheck fxs have already been called and returned true. 
============================================================================
*/
bool empl_in_dept_check(department dList[], int dCount, employee eList[], int eID, int dID)
{

    //Cycles though the dList indexes to get to the correct user entered dID
    for (int i = 0; i < dCount; i++)
    {
        if(dList[i].dID == dID)//Finds the user entered dID
        {

            /*
            empl_in_dept is an array of eList indexes. This 
            for-loop cycles through dList's empl_in_dept[j] indexes to check the user entered eID number 
            against a eList.eID.
            */
            for (int j = 0; j <= dList[i].empl_in_dept_count; j++)
            {


                if(dList[i].empl_in_dept_count == 0)//checks to see if no employees have been added to the department
                {
                    return false;
                }

                if(dList[i].empl_in_dept[j].eID != eID && j == dList[i].empl_in_dept_count)//check to see if the user entered eID already exists in the department
                {
                    return false;
                }

                if(dList[i].empl_in_dept[j].eID == eID)//if there is a match, return true
                {

                    return true;
                }
            }
        }
    }
}

/*
============================================================================
Function : addDepartment
Parameters : department dList[], int &dCount
Return : void fx
Description : This function adds department info to the dList array after checking if it already exists. It uses
dCount to specify what dList index to store info in
============================================================================
*/
void addDepartment(department dList[], int &dCount)
{

    int dID;//stores a department ID number to be checked and/or saved

    cout << "Enter in a department ID number: ";
    cin >> dID;
    cout << endl;

    if(dCheck(dList, dCount, dID))//check to see if the department already exists, true returns out of the function
    {
        cout << "This department already exists." << endl;
        cout << endl;
        return;
    }
    else//if the department does not exits, add it to the dList and add a department name as well
    {
        dList[dCount].dID = dID;//stores the user entered department number

        cout << "Enter in a department name: ";
        cin.ignore();//discards return carrage
        cin.getline(dList[dCount].dName, 40, '\n');//stores the user entered department name

        cout << endl;   

        cout << "Department " << dID <<  " has been added." << endl;

        dCount += 1;//increment the dCount by one 

        cout << endl;

        return;

    }

}

/*
============================================================================
Function : addEmployee
Parameters : employee eList[], int &eCount
Return : void fx
Description : This function adds employee info to the eList array after checking if it already exists. It uses
eCount to specify what eList index to store info in
============================================================================
*/
void addEmployee(employee eList[], int &eCount)
{
    int eID;//store the user entered employee ID number

    cout << "Enter in employee ID number: ";
    cin >> eID;
    cout << endl;

    if(eCheck(eList, eCount, eID))//checks to see if the employee already exists, true returns out of the function
    {
        cout << "This employee already exists" << endl;
        return;
    }
    else//if the employee does not exist, add employee info to eList
    {
        eList[eCount].eID = eID;

        cout << "Enter employee first name: ";
        cin.ignore();//discards return carrage
        cin.getline(eList[eCount].fName, 40, '\n');//saves employee's first name
        cout << endl;

        cout << "Enter employee last name: ";
        cin.getline(eList[eCount].lName, 40, '\n');//saves employee's last name
        cout << endl;

        cout <<"Enter employee salary: ";
        cin >> eList[eCount].salary;//saves employee's salary
        cout << endl;

        cout << "Employee " << eID <<  " has been added." << endl;

        eCount +=1;//increment eCount by one

        cout << endl;
        return;
    }
}

/*
============================================================================
Function : add_empl_to_dept
Parameters : department dList[], int dCount, employee eList[], int eCount
Return : void fx
Description : This function adds an employee to a department. It stores the employee in the empl_in_dept array
as a pointer to the address of an eList index. 
============================================================================
*/
void add_empl_to_dept(department dList[], int dCount, employee eList[], int eCount)
{

    int eID, dID;//these variables store the user entered employee and department ID

    cout << "Enter in department ID number: ";
    cin >> dID;
    cout << endl;

    if(dCheck(dList, dCount,dID))//checks if the department exists, if false, returns out of the function
    {

        cout << "Enter in an employee ID number: ";
        cin >> eID;
        cout << endl;

        if(eCheck(eList, eCount, eID))// check if an employee exists, if false, returns out of the function
        {

            if(empl_in_dept_check(dList, dCount, eList, eID, dID))//checks if an employee is already added to a department, if true, returns out of the function.
            {

                cout << "The employee has already been added to the department." << endl;
                return;
            }
            else//adds the user entered eID to the user entered dID
            {

                //for-loop cycles through dList searching for the user entered dID
                for(int i = 0; i <= dCount; i++)
                {

                    if(dList[i].dID == dID)//stops the for-loop at the user entered dID
                    {

                        //for-loop cycles through eList searching for the user entered eID
                        for(int j = 0; j <= eCount; j++)
                        {

                            if(eList[j].eID == eID)// stops the for-loop at the  user entered eID
                            {
                                dList[i].empl_in_dept[dList[i].empl_in_dept_count].eID = eList[j].eID;
                                strcpy(dList[i].empl_in_dept[dList[i].empl_in_dept_count].fName, eList[j].fName);
                                strcpy(dList[i].empl_in_dept[dList[i].empl_in_dept_count].lName, eList[j].lName);
                                dList[i].empl_in_dept[dList[i].empl_in_dept_count].salary = eList[j].salary;

cout << dList[i].empl_in_dept[dList[i].empl_in_dept_count].eID << endl
        << dList[i].empl_in_dept[dList[i].empl_in_dept_count].fName << endl
        << dList[i].empl_in_dept[dList[i].empl_in_dept_count].lName << endl
        << dList[i].empl_in_dept[dList[i].empl_in_dept_count].salary << endl;

                                cout << "Employee " << eID <<  " has been added to department " << dID << "." << endl;

                                dList[i].empl_in_dept_count += 1;//increments the department's employee count by one

                                cout << endl;

                                return;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            cout << "The employee does not exist." << endl;
            return;
        }
    }
    else
    {
        cout << "The department does not exist" << endl;
        return;
    }   

}

/*
============================================================================
Function : ePrint
Parameters : employee eList, int eCount
Return : void
Description : This function prints out a list all employee IDs, first and last names, and salaries
============================================================================
*/
void ePrint(employee eList[], int eCount)
{
    printf("----------------------------------------------------------\n");
    if(eCount == 0)//if there are no employees, prints None and returns out of the function
    {
        printf("Empl ID    | First Name        Last Name        | Salary\n");
        printf("----------------------------------------------------------\n");
        printf("None\n");
        printf("\n");
        return;
    }
    else
    {
        printf("Empl ID    | First Name        Last Name        | Salary\n");
        printf("----------------------------------------------------------\n");

        //for-loop cycles through the eList array and print out employee info for each index
        for(int i = 0; i < eCount; i++)
        {
            printf("%d         %s              %s               %.2f        \n", eList[i].eID, eList[i].fName, eList[i].lName, eList[i].salary);
        }
        printf("\n");
        return;
    }
}

/*
============================================================================
Function : dPrint
Parameters : department dList[], in dCount, employee eList[]
Return : void
Description : This function prints out a list all department IDs, department Names, and employees in the department
============================================================================
*/
void dPrint(department dList[], int dCount, employee eList[])
{
    printf("----------------------------------------------------------\n");
    if(dCount == 0)//if there are no departments, prints None and returns out of the function
    {
        printf("Dept ID    | Dept Name\n");
        printf("----------------------------------------------------------\n");
        printf("None\n");
        printf("\n");
        return;
    }
    else
    {

        //for-loop cycles through the dList array and print out department info for each index
        for(int i = 0; i < dCount; i++)
        {
            printf("Dept ID    | Dept Name\n");
            printf("----------------------------------------------------------\n");

            printf("%d         %s\n", dList[i].dID, dList[i].dName);

            printf("----------------------------------------------------------\n");
            printf("Empl ID    | First Name        Last Name        | Salary\n");
            printf("----------------------------------------------------------\n");

            if(dList[i].empl_in_dept_count == 0)//check to see if there are no employees in the department
            {
                printf("None\n");
                printf("\n");

            }
            else//prints out employees in department
            {
                //for-loop cycles through the empl_in_dept indexes and prints out employee info for each department
                for(int j = 0; j < dList[i].empl_in_dept_count; j++)
                {
                    printf("%d         %s              %s               %.2f        \n", dList[i].empl_in_dept[dList[i].empl_in_dept_count].eID, dList[i].empl_in_dept[dList[i].empl_in_dept_count].fName, dList[i].empl_in_dept[dList[i].empl_in_dept_count].lName, dList[i].empl_in_dept[dList[i].empl_in_dept_count].salary);
                }
                cout << endl;
            }


        }


        return;
    }
}

/*
============================================================================
Function : e_in_dPrint
Parameters : department dList[], in dCount, employee eList[]
Return : void
Description : This function prints out a list all employees in a department
============================================================================
*/
void e_in_dPrint(department dList[], int dCount, employee eList[])
{
    int dID; //stores the user entered department ID number

    cout << "Enter in a department ID number: ";
    cin >> dID;
    cout << endl;

    if(dCheck(dList, dCount, dID))//check to see if the department exists
    {
        //for-loop cycles through the dList to reach the user entered dID
        for(int i = 0; i < dCount; i++)
        {
            if(dList[i].dID == dID)//stops the for-loop at the user entered dID
            {
                printf("Dept ID    | Dept Name\n");
                printf("----------------------------------------------------------\n");
                printf("%d         %s\n", dList[i].dID, dList[i].dName);
                printf("----------------------------------------------------------\n");
                printf("Empl ID    | First Name        Last Name        | Salary\n");
                printf("----------------------------------------------------------\n");

                if(dList[i].empl_in_dept_count == 0)//check to see if there are no employees in the department
                {
                    printf("None\n");
                    printf("\n");
                    return;
                }
                else//prints out employees in department
                {
                    //for-loop cycles through the empl_in_dept indexes and prints out employee info for each department
                    for(int j = 0; j < dList[i].empl_in_dept_count; j++)
                    {
                        printf("%d         %s              %s               %.2f        \n", dList[i].empl_in_dept[dList[i].empl_in_dept_count].eID, dList[i].empl_in_dept[dList[i].empl_in_dept_count].fName, dList[i].empl_in_dept[dList[i].empl_in_dept_count].lName, dList[i].empl_in_dept[dList[i].empl_in_dept_count].salary);
                    }
                    cout << endl;
                    return;

                }
            }       
        }
    }
    else
    {
        cout << "That department does not exist." << endl;
        return;
    }
}

/*
============================================================================
Function : average
Parameters : department dList[], employee eList[]
Return : void
Description : This function prints out an average of employee salaries in a department
============================================================================
*/
void average(department dList[], int dCount, employee eList[])
{
    int dID;// stores the user entered deparment ID number
    int sum = 0; //stores the sum of the department employee's salary
    float average;

    cout << "Enter in a department ID number: ";
    cin >> dID;
    cout << endl;

    if(dCheck(dList, dCount, dID))//check to see if the department exists, returns out of the function if it does not
    {

        //for-loop cycles through dList to find the user entered dID
        for(int i = 0; i < dCount; i++)
        {
            if(dList[i].dID == dID)//stops the for-loop at the user entered dID
            {
                //for-loop cycles through the department's employees and adds up their salaries
                for(int j = 0; j < dList[i].empl_in_dept_count; j++)
                {
                    sum = (dList[i].empl_in_dept[j].salary + sum);
                }

                average = sum/dList[i].empl_in_dept_count;

                printf("Dept ID    | Dept Name            | Average\n");
                printf("----------------------------------------------------------\n");
                printf("%d         %s                   %.2f\n", dList[i].dID, dList[i].dName, average);

                cout << endl;

                return;
            }
        }
    }
    else
    {
        cout << "That department does not exist." << endl;
    }
}


/*
============================================================================
Function : save
Parameters : department dList[], int dCount, employee eList[], int eCount
Return : void
Description : This function all department and employee information into a file
============================================================================
*/
void save(department dList[], int dCount, employee eList[], int eCount)
{
    FILE *fp;//file pointer 
    char fileName [20];

    cout << "Enter in a name for the file to save to: ";
    cin.ignore();
    cin.getline(fileName, 20, '\n');// stores a user defined file name

    fp = fopen(fileName, "w");

    if(fp == NULL)//check to see if the file stream has been opened. if not return out of the function
    {
        cout << "The file did not open" << endl;
        return;
    }

    fprintf(fp, "%d\n", eCount);//prints the eCount to the file

    //for-loop cycles through eList and prints out employee info to the file
    for(int i = 0; i < eCount; i++)
    {
        fprintf(fp, "%d %s %s %f\n", eList[i].eID, eList[i].fName, eList[i].lName, eList[i].salary);
    }

    fprintf(fp, "%d\n", dCount);//prints the dCount to the file

    //for-loop cycles through dList and prints out department info to the file
    for(int i = 0; i < dCount; i++)
    {
        fprintf(fp, "%d %s %d ", dList[i].dID, dList[i].dName, dList[i].empl_in_dept_count);

        //for-loop cycles through dList's empl_in_dept array and prints out info to the file
        for(int j = 0; j < dList[i].empl_in_dept_count; j++)
        {
            fprintf(fp, "%d ", dList[i].empl_in_dept[j]);
        }
        fprintf(fp, "\n");

    }

    fclose(fp);//closes the file stream

}

/*
============================================================================
Function : load
Parameters : department dList[], int dCount, employee eList[], int eCount
Return : void
Description : This function loads all department and employee information from a file
============================================================================
*/
void load(department dList [], int &dCount, employee eList[], int &eCount)
{
    FILE *fp;//file pointer 
    char fileName [20];


    cout << "Enter in the name of the file to load: ";
    cin.ignore();
    cin.getline(fileName, 20, '\n');// stores a user defined file name

    fp = fopen(fileName, "r");

    if(fp == NULL)//check to see if the file stream has been opened. if not return out of the function
    {
        cout << "The file did not open" << endl;
        return;
    }


        fscanf(fp, "%d\n", &eCount);//prints the eCount to the file

        //for-loop cycles through eList and prints out employee info to the file
        for(int i = 0; i < eCount; i++)
        {

            fscanf(fp, "%d %s %s %f\n", &eList[i].eID, eList[i].fName, eList[i].lName, &eList[i].salary);
        }

        fscanf(fp, "%d\n", &dCount);//prints the dCount to the file

        //for-loop cycles through dList and prints out department info to the file
        for(int i = 0; i < dCount; i++)
        {
            fscanf(fp, "%d %s %d ", &dList[i].dID, dList[i].dName, &dList[i].empl_in_dept_count);

            //for-loop cycles through dList's empl_in_dept array and prints out info to the file
            for(int j = 0; j < dList[i].empl_in_dept_count; j++)
            {
                fscanf(fp, "%d ", &dList[i].empl_in_dept[j]);

            }
        }


    fclose(fp);//closes the file stream

}


/*
============================================================================
Function : printMenu
Parameters : none
Return : void
Description : This function prints the menu and prompt the user for an entry
============================================================================
*/

void printMenu()
{
    printf("----------------------------------------------------------\n"
           "Enter the number for the corresponding option:\n"
           "1 : Add a new department\n"
           "2 : Add a new employee\n"
           "3 : Add an employee to a department\n"
           "4 : Print a list of all employees\n"
           "5 : Print a list of all departments\n"
           "6 : Print a list of all employees in a department\n"
           "7 : Compute and print the average salary of a department\n"
           "8 : Save the full employee listing to a file\n"
           "9 : Load the full employee listing from a file\n"
           "10: Exit\n"
           "----------------------------------------------------------\n"
           "> ");

}

1 个答案:

答案 0 :(得分:0)

您将dList作为值传递,您需要通过引用或使用指针传递它。试试:

使用指针:

void addDepartment(department *dList, int &dCount)

参考:

void addDepartment(department &dList[], int &dCount)