Hi,
Ok I've got two programs here. The first one is simply asking for an employee's name and age and storing them in an array of structures, then displaying them. Works fine, woop-de-do...
Code:
#include <stdio.h>
#include <stdlib.h>
struct EMPLOYEE
{
char name[45];
int age;
};
void get_name (struct EMPLOYEE person []);
void disp_name (struct EMPLOYEE person []);
void main ()
{
struct EMPLOYEE person [5];
get_name (person , 5);
disp_name (person , 5);
getch ();
}
void get_name (struct EMPLOYEE person [])
{
int i = 0;
for (i = 0; i < 5; i ++)
{
printf ("Enter name: \n");
gets (person[i].name);
printf ("Enter age: \n");
scanf ("%d" , &person[i].age);
fflush (stdin);
}
}
void disp_name (struct EMPLOYEE person [])
{
int i = 0;
for (i = 0; i < 5; i ++)
{
printf ("Name is: %s \n" ,person[i].name );
printf ("Age is: %d \n" , person[i].age);
}
}
Now the second program, which is just a more worked up version is giving me a headache. I've taken the above example and 'tried' to get some user selection into it. The problem is the loop in the get_name function just runs and runs. It's supposed to populate an array of 5 structures! I'm thinking it's something to do with the switch statement, not passing the structure correctly?. Any advice would be really appreciated at this point.
Code:
#include <stdio.h>
#include <stdlib.h>
struct EMPLOYEE
{
char name[45];
int age;
};
int get_selection ();
void use_selection (int selection , struct EMPLOYEE person []);
void get_name (struct EMPLOYEE person []);
void disp_name (struct EMPLOYEE person []);
void main ()
{
struct EMPLOYEE person [5];
int selection = 0;
selection = get_selection ();
use_selection (selection , person);
getch ();
}
int get_selection ()
{
int selection = 0;
printf ("*** Main menu ***\n");
printf ("1.Add employee\n2.Display all employees\n3.Quit");
printf ("Enter choice: ");
do
{
scanf ("%d" , &selection);
fflush (stdin);
if ((selection < 1) || (selection > 5))
{
printf ("Invalid selection. Please re-enter: ");
}
}while((selection < 1) || (selection > 5));
return (selection);
}
void use_selection (int selection , struct EMPLOYEE person[])
{
do
{
switch (selection)
{
case 1 :
get_name (person , 5);
break;
case 2 :
disp_name (person , 5);
break;
case 3 :
printf ("Exiting");
break;
}
}while(selection != 3);
}
void get_name (struct EMPLOYEE person [])
{
int i = 0;
for (i = 0; i < 5; i ++)
{
printf ("Enter name: \n");
gets (person[i].name);
printf ("Enter age: \n");
scanf ("%d" , &person[i].age);
fflush (stdin);
}
}
void disp_name (struct EMPLOYEE person [])
{
int i = 0;
for (i = 0; i < 5; i ++)
{
printf ("Name is: %s \n" ,person[i].name );
printf ("Age is: %d \n" , person[i].age);
}
}