I'm having trouble with a small segment of code which should find out wether the number entered is less than or equal to zero. The do while loop asking for employee age wont seem to work. When ever I enter a negative number it accepts it and won't carrying on prompting for a correct age.
Code:
/* Add new employee to database */
static void menu_add_employee(char *line)
{
new_employee = malloc(sizeof(struct Employee));
fprintf ( stderr, "Enter employee name:\n");
read_line(stdin, line, MAX_NAME_LENGTH);
strcpy (new_employee->name, line);
do
{
fprintf ( stderr, "Enter employee sex:\n");
read_line(stdin, line, 2);
new_employee->sex = *line;
} while((line[0] != 'M')&&(line[0] != 'F'));
do
{
fprintf ( stderr, "Enter employee age:\n");
read_line(stdin, line, 4);
new_employee->age = *line;
} while((new_employee->age) <= 0);
fprintf ( stderr, "Enter employee job:\n");
read_line(stdin, line, MAX_JOB_LENGTH);
strcpy (new_employee->job, line);
new_employee->next = NULL;
if (employee_list_start==NULL)
employee_list_start = new_employee;
employee_list_end = new_employee;
}
Here is the structure definition:
Code:
/* Employee structure */
struct Employee
{
char name[MAX_NAME_LENGTH+1]; /* name string */
char sex; /* sex identifier, either 'M' or 'F' */
int age; /* age */
char job[MAX_JOB_LENGTH+1]; /* job string */
/* pointers to previous and next employee structures in the linked list */
struct Employee *prev, *next;
};
static struct Employee *employee_list_start = NULL;
static struct Employee *employee_list_end = NULL;
struct Employee *new_employee;
Here is the code for the read_line function :
Code:
/* Read line of characters from file pointer "fp", copying the characters
into the "line" string, up to a maximum of "max_length" characters, plus
one for the string termination character '\0'. Reading stops upon
encountering the end-of-line character '\n', for which '\0' is substituted
in the string. If the end of file character EOF is reached before the end
of the line, the failure condition (-1) is returned. If the line is longer
than the maximum length "max_length" of the string, the extra characters
are read but ignored. Success is returned (0) on successfully reading
a line */
static int read_line ( FILE *fp, char *line, int max_length )
{
int i;
char ch;
/* initialize index to string character */
i = 0;
/* read to end of line, filling in characters in string up to its
maximum length, and ignoring the rest, if any */
for(;;)
{
/* read next character */
ch = fgetc(fp);
/* check for end of file error */
if ( ch == EOF )
return -1;
/* check for end of line */
if ( ch == '\n' )
{
line[i] = '\0';
return 0;
}
/* fill character in string if it is not already full*/
if ( i < max_length )
line[i++] = ch;
}
/* the program should never reach here */
return -1;
}