Originally Posted by
Dave_Sinkula
I didn't get any output because get_itinerary returned 0 running through your example. Shouldn't the counter be incremented before the break?
Correct. It was a last minute change on the IDE that I forgot to report on my editor from wher I do the copy and paste.
And wouldn't it be better to consistently use size_t for the counter?
Agreed.
Last version:
Code:
/*******************************************************
* Purpose: Design an airline reservation structure that contains the
* following data:
*
* Flight Number
* Originating Airport Code (3 characters)
* Destination Airport Code (3 characters)
* Starting time
* Arrival time
***************************************************************/
#include <stdio.h>
#include <string.h>
struct itinerary
{
int flight; /* Flight number */
char origin_airport[4]; /* Airport of origin */
char dest_airport[4]; /* Destination airport */
int start_time; /* Time of start of flight */
int arrival_time; /* Time of arrival */
};
static void print_itinerary (struct itinerary const *list, size_t counter)
{
size_t i; /* Index to cycle through the program */
for (i = 0; i < counter; i++)
{
struct itinerary const *p = list + i;
printf ("Flight: %d\n", p->flight);
printf ("Origin Airport: %s\n", p->origin_airport);
printf ("Desination Airport %s\n", p->dest_airport);
printf ("Start: %d\n", p->start_time);
printf ("Arrive: %d\n", p->arrival_time);
printf ("\n");
}
return;
}
static size_t get_itinerary (struct itinerary *list, size_t nb)
{
char line[10]; /* Input from the user */
size_t counter = 0; /* Counter for loop starts at zero */
while (counter < nb)
{
struct itinerary *p = list + counter;
counter++;
printf ("Enter the flight number : ");
fgets (line, sizeof line, stdin);
sscanf (line, "%d", &p->flight);
printf ("Enter the airport origin : ");
fgets (line, sizeof line, stdin);
*p->origin_airport = 0;
strncat (p->origin_airport, line, sizeof p->origin_airport - 1);
printf ("Enter the destination airport: ");
fgets (line, sizeof line, stdin);
*p->dest_airport = 0;
strncat (p->dest_airport, line, sizeof p->dest_airport - 1);
printf ("Enter the start time : ");
fgets (line, sizeof line, stdin);
sscanf (line, "%d", &p->start_time);
printf ("Enter the arrival time : ");
fgets (line, sizeof line, stdin);
sscanf (line, "%d", &p->arrival_time);
printf ("Do you wish to enter another flight? (<enter>=yes or n=no) ");
fgets (line, sizeof line, stdin);
{
char quit; /* Variable used to exit loop */
sscanf (line, "%c", &quit);
if (quit == 'n')
break;
}
}
return counter;
}
int main ()
{
enum
{
MAX_ENTRIES = 50
}; /* Max number of stucts to create */
struct itinerary list[MAX_ENTRIES]; /* Array of structures for data */
size_t counter = get_itinerary (list, MAX_ENTRIES);
print_itinerary (list, counter);
(void) getchar ();
return 0;
}