2013-03-04 2 views
1

Я хочу заполнить третий параметр для каждого массива структуры employeeData (часы).Передача структуры с помощью функции

Я хотел бы запросить ручной ввод в раздел часов, спросив «Пожалуйста, введите часы для сотрудника x», как показано ниже. Однако это не работает.

void Get_input (long id_number[], float hours[], int num_empl) 
    { 
    /*Local Variable Declaration */ 

int i; /* Variable used in loop counter */ 

    /* Gets number of employee hours and stores them in an array. */ 

for (i = 0; i < num_empl; ++i) 
    { 
    printf("\nEnter the numbers of hours worked by employee # %06li: ", 
      employeeData[i].id_number); 
    scanf ("%f", &employeeData[i].hours); 
    } 

printf("\n\n"); 
} 

Вот моя полная «программа» до сих пор:

/*Define and Includes */ 

#include <stdio.h> 
#include <cstdlib> 

/* Define Constants */ 
#define NUM_EMPL 5 
#define OVERTIME_RATE 1.5f 
#define STD_WORK_WEEK 40f 

/* Define a global structure to pass employee data between functions */ 

struct employee 
{ 
long id_number; 
float wage; 
float hours; 
float overtime; 
float gross; 
}; 

/* define prototypes here for each function except main */ 

/************************************************************************/ 
/*      Function: Get_input        */ 
/*                  */ 
/* Purpose: Obtains input from user, the number of hours worked per */ 
/*    employee and stores the results in an array that is  */ 
/*    passed back to the calling program by reference.  */ 
/*                  */ 
/* Parameters: clockNum- Array of employee clock numbers.    */ 
/*    hours- Array of number of hours worked by an employee */ 
/*    size- Number of employees to process     */ 
/*                  */ 
/* Returns: Nothing, since 'clockNum' & 'hours' arrays are passed by */ 
/*    reference.            */ 
/************************************************************************/ 

void Get_input (long id_number[], float hours[], int num_empl) 
{ 
    /*Local Variable Declaration */ 

int i; /* Variable used in loop counter */ 

    /* Gets number of employee hours and stores them in an array. */ 

for (i = 0; i < num_empl; ++i) 
    { 
    printf("\nEnter the numbers of hours worked by employee # %06li: ", 
      employeeData[i].id_number); 
    scanf ("%f", &employeeData[i].hours); 
    } 

    printf("\n\n"); 
    } 

    void Output_results_screen (struct employee [ ], int num_empl); 


    /************************************************************************* 
    **      Function: Output_results_screen     
    **                  
    ** Purpose: Outputs to screen in a table format the following   
    **      information about an employee: Clock, Wage,  
    **      Hours, Overtime, and Gross Pay.     
    **                  
    ** Parameters: employeeData - an array of structures containing   
    **        employee information      
    **    size - number of employees to process     
    **                  
    ** Returns: Nothing (void)           
    **                  
    *************************************************************************/ 

    void Output_results_screen (struct employee employeeData[], int num_empl) 
    { 
    int i; /* loop index */ 

     printf ("-----------------------------------------\n"); /*Print Header To Screen */ 
     printf ("Clock# \t Wage \t Hours \t OT \t Gross\n"); 
     printf ("-----------------------------------------\n"); 

    /* printf information about each employee */ 
    for (i = 0; i < num_empl ; ++i) 
    { 


     printf("%06li %5.2f %4.1f %4.1f %8.2f \n", 
        employeeData[i].id_number, employeeData[i].wage, employeeData[i].hours, 
        employeeData[i].overtime, employeeData[i].gross); 
    } /* for */ 

    } /* Output_results_screen */ 


    int main() 
    { 


    /* Variable Declaration and initialization */ 
    struct employee employeeData[NUM_EMPL] = { 
    { 98401, 10.60 }, 
    { 526488, 9.75 }, 
    { 765349, 10.50 }, 
    { 34645, 12.25 }, 
    { 127615, 8.35 } 
    }; 


    /* Call various functions needed to reading, calculating, and printing as needed */ 

     /* Function call to get input from user. */ 
Get_input (id_number, hours, NUM_EMPL); 

    /* Function call to output results to the screen in table format. */ 
    Output_results_screen (employeeData, NUM_EMPL); 
    system("pause"); 
    return(0); /* success */ 

    } /* main */ 
+0

Какая ошибка? Кажется, я не вижу ошибок в вашем коде – TravellingGeek

+0

. Первая ошибка - это 66 'employeeData 'undeclared (сначала используйте эту функцию), которая входит в строку 66, где говорится:« employeeData [i] .id_number » – Americo

+0

Я согласен с @ Ответ LaceySnr ниже, вам нужно передать employeeData в Get_Input, как вы делали в Output_results_screen, потому что он локальный в основной функции – TravellingGeek

ответ

2

employeeData является локальным для main и не может рассматриваться в GetInput() поэтому я предполагаю, что вы получаете ошибку компилятора.

Поместите этот массив вне всех ваших функций вверху (т. Е. Сделайте его глобальным), и он должен работать. Или передайте указатель на массив на GetInput, чтобы вы могли прочитать соответствующую запись.

+0

проблема решен! как вы сказали @GeraldSV, путь сюда - передать указатель на массив GetInput. После того как я прошел всю структуру, функция распознала параметры. Спасибо! – Americo

Смежные вопросы