Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

Commentaires sur code source (long)

48 réponses
Avatar
Eddahbi Karim
Bonjour à tous,

J'suis rentré de vacanes et me revoici avec mes exos de C. Cette fois ci
crée une structure pour stocker les informations d'un vol.

Si vous avez tout commentaire sur le code, de manière à l'améliorer,
faites en part :-).

/*-8<-----------------------------------------------------------------

flight_reservation.c -- This program simulate a flight reservation

Author : Eddahbi Karim
E-mail : non.tu.ne.me.connais.pas.spavrai@ifrance.com Nick :
ThE_TemPLaR (newsgroups/Forums)

----------------------------------------------------------------------

Usage : Launch the program and enter the airport codes,
the flight number, the starting time and the arrival time.

Warning : Time must contain 2 digits : 2 digits. Not more, not
less.

----------------------------------------------------------------->8-*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

/*--------------------------------------------------------------------

USAGE : Calculate the first dimension of a two dimensions array

PARAMETER : Two dimensional array

--------------------------------------------------------------------*/

#define FIRST_DIM_SIZE(array) sizeof((array)) / sizeof((array[0]))

/************************Structures***********************************

Reservation

Contains :
- flight_nb[6] : The flight number ( 4 digits max )
- orig_air_code[5] : The origin airport code ( 3 letters )
- dest_air_code[5] : The destination airport code ( 3 letters )
- start_time[7] : Starting time [2 digits : 2 digits]
- end_time[7] : Arrival time [2 digits : 2 digits]

*********************************************************************/

typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;

/*********************************************************************

NAME : wipestring( string )

USAGE : Wipe useless values from the string...

PARAMETERS : char const *string to wipe...

*********************************************************************/

static void
wipestring (char const *string)
{
/* We search a '\n' character */
char *p = strchr (string, '\n');

/* We found it, we replace it by '\0' */ if (p)
{
*p = '\0';
}

/* We don't find it, so we get everything pending in stdin */ else
{
int c;

while ((c = getchar ()) != '\n' && c != EOF) {
}
}
}

/*********************************************************************

NAME : getstring ( string, size )

USAGE : Take the user input and verify it...

PARAMETERS :
- The string to check and to fill if the user enter something - The
size of the string

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
getstring (char *string, size_t size) {
/* The error number */
int err = EXIT_SUCCESS;

/* Check if there's an input */
if (fgets (string, (int) size, stdin) == NULL) {
(void) printf ("Input Error\n");
err = EXIT_FAILURE;
}

else
{
/* Is the input too large ? */
if ( strchr(string, '\n') == NULL )
{
(void) printf("Input too large.\n");
wipestring(string);
err = EXIT_FAILURE;
}

/* If we got a '\n', does he enter something ? */ if ( err ==
EXIT_SUCCESS )
{

/* Wipe useless values */
wipestring (string);

if (*string == '\0')
{
(void) printf ("No input\n");
err = EXIT_FAILURE;
}

}
}

return err;
}

/*********************************************************************

NAME : get_answer( *string, input_size )

USAGE : Print an input area with a space determined by the size of
the value to take and take the value.

PARAMETERS :
- The string to store the input.
- The size of this input.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
get_answer ( char *string, size_t input_size ) {
/* Exit status */
int err = EXIT_SUCCESS;

/* Variable used for repetitions */
size_t i = 0;

/* If we can't write anything in the string, this is useless */ #ifdef
DEBUG
if ( input_size < 3 )
{
(void) fprintf(stderr, "Input size allocated too small !"); err =
EXIT_FAILURE;
} else
#endif /* DEBUG */

{

/* Information about the number of char authorized */ (void)
printf("(%d char max)", (int) input_size - 2);

(void) printf("[");

/* sizeof returns the real size of an array, but for a string
we got 2 reserved places ( "string\n\0" ) */

/* Design the input area */
for (i = 0; i < input_size - 2; i++ ) {
(void) printf("-");
}

(void) printf("]");

/* stdin got ( input_size - 2 ) + 1 char, to put the user
inside the input area we go (input_size - 1) chars back */

/* Put the user inside the input area */ for (i = 0; i <
input_size - 1; i++ ) {
(void) printf("\b");
}


}

/* If nothing is wrong, grab the user value */ if ( err ==
EXIT_SUCCESS )
{
err = getstring(string, input_size);
}

return err;

}

/*********************************************************************

NAME : checkcode ( *string, input_size )

USAGE : Check the airport code entered by the user.

PARAMETERS :
- The airport code
- Its size.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
checkcode ( char *string, size_t input_size ) {
/* Exit status */
int err = EXIT_SUCCESS;

/* The code number */
int number = 0;

/* The airport codes */
char codes[][5] = { "JPU", "NYC", "TYO", "TXL", "LCY", "HKG" };

#ifdef DEBUG

/* We check if the pointer points to something */ if ( string == NULL
)
{
(void) fprintf(stderr, "Invalid string pointer"); err =
EXIT_FAILURE;
}

/* The input_size must be equal to 5 (XXX\n\0) */ else if ( input_size
!= 5 )
{
(void) fprintf(stderr, "Input under/oversized."); err =
EXIT_FAILURE;
} else

#endif /* DEBUG*/

/* We get the airport code */
if ( err == EXIT_SUCCESS )
err = get_answer(string, input_size);

/* We check if the code is correct */ if ( err == EXIT_SUCCESS )
{
/* We reset the exit status */
err = EXIT_FAILURE;

/* The code is compared to each code in the code database */ for
(number = 0; number < FIRST_DIM_SIZE(string) + 1 &&
err != EXIT_SUCCESS; number++)
{
if ( strcmp(string, codes[number]) == 0 )
err = EXIT_SUCCESS;
}

/* If the user entered a wrong code, say it to him */ if ( err ==
EXIT_FAILURE )
(void) printf("Wrong airport code");
}

return err;
}

/*********************************************************************

NAME : checktime ( *string, input_size )

USAGE : Check if the user entered a valid time.

PARAMETERS :
- Time entered by the user
- Input size

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
checktime (char *string, size_t input_size) {
/* Exit status */
int err = EXIT_SUCCESS;

/* Time values : Hour and minutes */
unsigned short int time[2] = { 0, 0 };

/* Debug : We check if the pointer is valid */ #ifdef DEBUG
if ( string == NULL )
{
(void) fprintf(stderr, "Invalid string pointer.\n"); err =
EXIT_FAILURE;
}

/* Debug : We check if the input_size is correct
It must be 7 ( xx:xx\n\0 ) */
else if ( input_size != 7 )
{
(void) fprintf(stderr, "Input under/oversized. Must be 7.\n"); err
= EXIT_FAILURE;
}
#endif /* DEBUG */

/* We get the time */
err = get_answer(string, input_size);

/* We verify if the user put the separator */ if ( string[2] != ':' )
{
(void) puts("Wrong separator or not placed correctly"); err =
EXIT_FAILURE;
}

/* We check if the user doesn't enter a letter at the end */ else if (
isdigit(string[4]) == 0 )
{
(void) puts("Wrong values");
err = EXIT_FAILURE;
}

/* We check if the user entered two numbers */ else if (
sscanf(string, "%02hu:%02hu", &time[0], &time[1]) != 2 ) {
(void) puts("Wrong values");
err = EXIT_FAILURE;
}

/* Are the time values correct ? */
else if ( ( time[0] > 23 ) || ( time[1] > 59 ) ) {
(void) puts("Wrong time, the maximal value for the hour is 23");
err = EXIT_FAILURE;
}

return err;

}

/*********************************************************************

NAME : ask ( *client_fl )

USAGE : Take the principal informations about the flight and do
some basic check.

PARAMETER : The client reservation data structure.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
ask ( reservation *client_fl )
{
/* Error status */
int err = EXIT_SUCCESS;

assert( client_fl != NULL );

/* We check if the pointer point to something */ if ( client_fl ==
NULL )
{
(void) fprintf(stderr, "Data structure pointer client_fl is
invalid"); err = EXIT_FAILURE;
}

/* If everything is ok, we ask the first question */ else {
(void) puts("What's the starting airport code :");

err = checkcode(client_fl->orig_air_code,
sizeof(client_fl->orig_air_code));
}

/* Ok ? Next question */
if ( err == EXIT_SUCCESS )
{
(void) puts("What's the destination airport code :");

err = checkcode(client_fl->dest_air_code,
sizeof(client_fl->dest_air_code));
}

/* The flight number */
if ( err == EXIT_SUCCESS )
{
(void) puts("What's your flight number :");

err = get_answer(client_fl->flight_nb,
sizeof(client_fl->flight_nb));
}

/* Starting and arrival time */
if ( err == EXIT_SUCCESS )
{
(void) puts("The flight will start at : ( Valid times are 00:00 ->
23:59 )"); err = checktime(client_fl->start_time,
sizeof(client_fl->start_time));
}

if ( err == EXIT_SUCCESS )
{
(void) puts("The plane will arrive at : ( Valid times are 00:00 ->
23:59 )"); err = checktime(client_fl->end_time,
sizeof(client_fl->end_time));
}

/* If everything is ok, we print the user's flight information */ if (
err == EXIT_SUCCESS )
{
(void) printf("You start from | %s\n"
"You'll fly to | %s\n"
"Your flight number is | %s\n"
"The plane will lift off at | %s\n"
"The plane will arrive at | %s\n",
client_fl->orig_air_code,
client_fl->dest_air_code,
client_fl->flight_nb,
client_fl->start_time,
client_fl->end_time);
}

return err;

}

/*********************************************************************

NAME : aircodes ( void )

USAGE : Display program version and airport codes.

*********************************************************************/

static void
aircodes ( void )
{
(void) puts("Flight reservation v0.1"); (void)
puts("---------------------------------------------------------");
(void) puts("Airport codes :");
(void) printf("\nJPU - Paris La Defense\n"
"NYC - New York Multiple City Code\n" "TYO - Tokyo Narita\n"
"TXL - Berlin Tegel\n"
"LCY - London City\n"
"HKG - Hong Kong Intl\n");
(void)
printf("---------------------------------------------------------\n\n");
}

int main ( void )
{
/* Final exit status */
int err = EXIT_SUCCESS;

/* The data structure which contains client flight informations */
reservation client_fl = {{0}, {0}, {0}, {0}, {0}};

/* Display the airport codes */
aircodes();

/* Get the client flight informations */ (void) puts("Welcome.");

err = ask( &client_fl );

return err;
}

10 réponses

1 2 3 4 5
Avatar
Eddahbi Karim
Désolé pour l'identation, c'est la dernière fois que j'utilise Recoupe du
texte avec mon lecteur de news...
Avatar
Yves ROMAN

Bonjour à tous,

J'suis rentré de vacanes et me revoici avec mes exos de C. Cette fois ci
crée une structure pour stocker les informations d'un vol.

Si vous avez tout commentaire sur le code, de manière à l'améliorer,
faites en part :-).

[...]


#define FIRST_DIM_SIZE(array) sizeof((array)) / sizeof((array[0]))



Je mettrais plutot:
#define FIRST_DIM_SIZE(array) (sizeof(array) / sizeof((array)[0]))

[...]

/************************Structures***********************************

Reservation

Contains :
- flight_nb[6] : The flight number ( 4 digits max )
- orig_air_code[5] : The origin airport code ( 3 letters )
- dest_air_code[5] : The destination airport code ( 3 letters )
- start_time[7] : Starting time [2 digits : 2 digits]
- end_time[7] : Arrival time [2 digits : 2 digits]

*********************************************************************/

typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;


Il y a 1 caractère en plus dans chaque chaine : d'après le code qui suit, tu
stockes le 'n' dedans. Pourquoi ?


/*********************************************************************

NAME : wipestring( string )

USAGE : Wipe useless values from the string...

PARAMETERS : char const *string to wipe...

*********************************************************************/

static void
wipestring (char const *string)
{
/* We search a 'n' character */
char *p = strchr (string, 'n');

/* We found it, we replace it by '' */ if (p)
{
*p = '';
}


Je ne trouve pas une bonne idee de mettre le commentaire avant l'instruction sur
la meme ligne car on risque de ne plus voir l'instruction.
Je ferais plutot
/* We found it, we replace it by '' */
if (p)
ou
if (p) /* We found it, we replace it by '' */


[...]

/*********************************************************************

NAME : getstring ( string, size )

USAGE : Take the user input and verify it...

PARAMETERS :
- The string to check and to fill if the user enter something - The
size of the string

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/



Si toutes tes saisies passent par ici, il serait plus logique de faire en sorte
que cette fonction enleve le 'n' des chaines, plutot que de le garder dans les
chaines.

[...]
/*********************************************************************

NAME : checkcode ( *string, input_size )

USAGE : Check the airport code entered by the user.

PARAMETERS :
- The airport code
- Its size.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int
checkcode ( char *string, size_t input_size ) {
/* Exit status */
int err = EXIT_SUCCESS;

/* The code number */
int number = 0;

/* The airport codes */
char codes[][5] = { "JPU", "NYC", "TYO", "TXL", "LCY", "HKG" };


Ici les codes ne contiennent pas n


#ifdef DEBUG

/* We check if the pointer points to something */ if ( string == NULL
)
{
(void) fprintf(stderr, "Invalid string pointer"); err > EXIT_FAILURE;
}

/* The input_size must be equal to 5 (XXXn) */ else if ( input_size
!= 5 )
{
(void) fprintf(stderr, "Input under/oversized."); err > EXIT_FAILURE;
} else

#endif /* DEBUG*/

/* We get the airport code */
if ( err == EXIT_SUCCESS )
err = get_answer(string, input_size);

/* We check if the code is correct */ if ( err == EXIT_SUCCESS )
{
/* We reset the exit status */
err = EXIT_FAILURE;

/* The code is compared to each code in the code database */ for
(number = 0; number < FIRST_DIM_SIZE(string) + 1 &&


(number = 0; number < FIRST_DIM_SIZE(codes) &&

err != EXIT_SUCCESS; number++)
{
if ( strcmp(string, codes[number]) == 0 )


Avec ou sans n ?

err = EXIT_SUCCESS;
}

/* If the user entered a wrong code, say it to him */ if ( err = > EXIT_FAILURE )
(void) printf("Wrong airport code");
}

return err;
}



[...]


/*********************************************************************

NAME : aircodes ( void )

USAGE : Display program version and airport codes.

*********************************************************************/

static void
aircodes ( void )
{
(void) puts("Flight reservation v0.1"); (void)
puts("---------------------------------------------------------");
(void) puts("Airport codes :");
(void) printf("nJPU - Paris La Defensen"
"NYC - New York Multiple City Coden" "TYO - Tokyo Naritan"
"TXL - Berlin Tegeln"
"LCY - London Cityn"
"HKG - Hong Kong Intln");
(void)
printf("---------------------------------------------------------nn");
}


Dommage que les codes aeroport apparaisent en double dans checkcode () et dans
aircodes ()
Il vaudrait mieux declarer une variable globale
struct {
char * code ;
char * libelle ;
} liste_codes[] {
{ "JPU" , "Paris La Defense" } ,
{ "NYC" , "New York Multiple City Code" } ,
{ "TYO" , "Tokyo Narita" } ,
{ "TXL" , "Berlin Tegel" } ,
{ "LCY" , "London City" } ,
{ "HKG" , "Hong Kong Intl" } ,
{ NULL , NULL }
} ;

qui serait utilisee par ces 2 fonctions

Avatar
Eddahbi Karim

[...]


Je mettrais plutot:
#define FIRST_DIM_SIZE(array) (sizeof(array) / sizeof((array)[0]))


Ok :)

[...]


typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;


Il y a 1 caractère en plus dans chaque chaine : d'après le code qui suit, tu
stockes le 'n' dedans. Pourquoi ?


Car je vais prendre les valeurs à l'aide de fgets qui stocke le n :).

[snip]

/* We found it, we replace it by '' */ if (p)
{
*p = '';
}


Je ne trouve pas une bonne idee de mettre le commentaire avant l'instruction sur
la meme ligne car on risque de ne plus voir l'instruction.
Je ferais plutot


Désolé mais c'est la recoupe du texte qui à donner ce truc horrible :/
La prochaine fois je le ferais plus :).

/* We found it, we replace it by '' */
if (p)


Je préfère celle là.
ou
if (p) /* We found it, we replace it by '' */



[...]

Si toutes tes saisies passent par ici, il serait plus logique de faire en sorte
que cette fonction enleve le 'n' des chaines, plutot que de le garder dans les
chaines.


Je vais voir mais on y gagne quoi ? de la taille allouée en mémoire ?


[...]


/* The airport codes */
char codes[][5] = { "JPU", "NYC", "TYO", "TXL", "LCY", "HKG" };


Ici les codes ne contiennent pas n


Effectivement



{
if ( strcmp(string, codes[number]) == 0 )


Avec ou sans n ?


Sans sucre euuuh... c'est vrai que ça me parait étrange mais ça marche...

[...]

Dommage que les codes aeroport apparaisent en double dans checkcode () et dans
aircodes ()
Il vaudrait mieux declarer une variable globale
struct {
char * code ;
char * libelle ;
} liste_codes[] > {
{ "JPU" , "Paris La Defense" } ,
{ "NYC" , "New York Multiple City Code" } ,
{ "TYO" , "Tokyo Narita" } ,
{ "TXL" , "Berlin Tegel" } ,
{ "LCY" , "London City" } ,
{ "HKG" , "Hong Kong Intl" } ,
{ NULL , NULL }
} ;

qui serait utilisee par ces 2 fonctions


Effectivement c'est pas mal comme idée, je vais voir comment je peux
faire.

Merci :),
Voila,
ThE_TemPLaR.


Avatar
Emmanuel Delahaye
In 'fr.comp.lang.c', Eddahbi Karim
wrote:

Bonjour à tous,

J'suis rentré de vacanes et me revoici avec mes exos de C. Cette fois ci
crée une structure pour stocker les informations d'un vol.

Si vous avez tout commentaire sur le code, de manière à l'améliorer,
faites en part :-).



C'est pas mal. Quelques remarques (-ed-) + la redirection systématique des
erreurs vers stderr. Mise en page par GNU Indent...

/*-8<-----------------------------------------------------------------

flight_reservation.c -- This program simulate a flight reservation

Author : Eddahbi Karim
E-mail : Nick :
ThE_TemPLaR (newsgroups/Forums)

----------------------------------------------------------------------

Usage : Launch the program and enter the airport codes,
the flight number, the starting time and the arrival time.

Warning : Time must contain 2 digits : 2 digits. Not more, not
less.

----------------------------------------------------------------->8-*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

/*--------------------------------------------------------------------

USAGE : Calculate the first dimension of a two dimensions array

PARAMETER : Two dimensional array

--------------------------------------------------------------------*/

#define FIRST_DIM_SIZE(array) sizeof((array)) / sizeof((array[0]))

/************************Structures***********************************

Reservation

Contains :
- flight_nb[6] : The flight number ( 4 digits max )
- orig_air_code[5] : The origin airport code ( 3 letters )
- dest_air_code[5] : The destination airport code ( 3 letters )
- start_time[7] : Starting time [2 digits : 2 digits]
- end_time[7] : Arrival time [2 digits : 2 digits]

*********************************************************************/

typedef struct
{
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
}
reservation;

/*********************************************************************

NAME : wipestring( string )

USAGE : Wipe useless values from the string...

PARAMETERS : char const *string to wipe...

*********************************************************************/

static void wipestring (char const *string)
{
/* We search a 'n' character */
char *p = strchr (string, 'n');

/* We found it, we replace it by '' */ if (p)
{
*p = '';
}

/* We don't find it, so we get everything pending in stdin */
else
{
int c;

while ((c = getchar ()) != 'n' && c != EOF)
{
}
}
}

/*********************************************************************

NAME : getstring ( string, size )

USAGE : Take the user input and verify it...

PARAMETERS :
- The string to check and to fill if the user enter something - The
size of the string

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/
static int getstring (char *string, size_t size)
{
/* The error number */
int err = EXIT_SUCCESS;

/* Check if there's an input */
if (fgets (string, (int) size, stdin) == NULL)
{
(void) fprintf (stderr, "Input Errorn");
err = EXIT_FAILURE;
}
else
{
/* Is the input too large ? */
if (strchr (string, 'n') == NULL)
{
(void) fprintf (stderr, "Input too large.n");
wipestring (string);
err = EXIT_FAILURE;
}

/* If we got a 'n', does he enter something ? */
if (err == EXIT_SUCCESS)
{

/* Wipe useless values */
wipestring (string);

if (*string == '')
{
(void) fprintf (stderr, "No inputn");
err = EXIT_FAILURE;
}
}
}

return err;
}

/*********************************************************************

NAME : get_answer( *string, input_size )

USAGE : Print an input area with a space determined by the size of
the value to take and take the value.

PARAMETERS :
- The string to store the input.
- The size of this input.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/
static int get_answer (char *string, size_t input_size)
{
/* Exit status */
int err = EXIT_SUCCESS;

/* Variable used for repetitions */
size_t i = 0;

/* If we can't write anything in the string, this is useless */
#ifdef DEBUG
if (input_size < 3)
{
(void) fprintf (stderr, "Input size allocated too small !");
err = EXIT_FAILURE;
}
else
#endif /* DEBUG */
{
/* Information about the number of char authorized */
(void) printf ("(%d char max)", (int) input_size - 2);

(void) printf ("[");

/* sizeof returns the real size of an array, but for a string
we got 2 reserved places ( "stringn" ) */

/* Design the input area */
for (i = 0; i < input_size - 2; i++)
{
(void) printf ("-");
}

(void) printf ("]");

/* stdin got ( input_size - 2 ) + 1 char, to put the user
inside the input area we go (input_size - 1) chars back */

/* Put the user inside the input area */
for (i = 0; i < input_size - 1; i++)
{
(void) printf ("b");
}

/* -ed- : La norme ne garantit la sortie effective.
* Pour un usage portable, il faut forcer
* l'emission de caracteres:
*/
fflush (stdout);
}

/* If nothing is wrong, grab the user value */
if (err == EXIT_SUCCESS)
{
err = getstring (string, input_size);
}

return err;
}

/*********************************************************************

NAME : checkcode ( *string, input_size )

USAGE : Check the airport code entered by the user.

PARAMETERS :
- The airport code
- Its size.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int checkcode (char *string, size_t input_size)
{
/* Exit status */
int err = EXIT_SUCCESS;

/* The code number */
int number = 0;

/* The airport codes */
char codes[][5] {"JPU", "NYC", "TYO", "TXL", "LCY", "HKG"};

#ifdef DEBUG

/* We check if the pointer points to something */
if (string == NULL)
{
(void) fprintf (stderr, "Invalid string pointer");
err = EXIT_FAILURE;
}

/* The input_size must be equal to 5 (XXXn) */
else if (input_size != 5)
{
(void) fprintf (stderr, "Input under/oversized.");
err = EXIT_FAILURE;
}
else
#endif /* DEBUG */

/* We get the airport code */
if (err == EXIT_SUCCESS)
{
err = get_answer (string, input_size);
}
/* We check if the code is correct */ if (err == EXIT_SUCCESS)
{
/* We reset the exit status */
err = EXIT_FAILURE;

/* The code is compared to each code in the code database */
#if 0
/* -ed- : Probablement tres faux.
* La taille qui nous interesse
* est celle du tableau de reference.
* 'string' est un pointeur
*/
for (number = 0
; number < FIRST_DIM_SIZE (string) + 1
&& err != EXIT_SUCCESS
; number++)
#else
for (number = 0
; number < FIRST_DIM_SIZE (codes)
&& err != EXIT_SUCCESS
; number++)
#endif
{
if (strcmp (string, codes[number]) == 0)
{
err = EXIT_SUCCESS;
}
}

/* If the user entered a wrong code, say it to him */
if (err == EXIT_FAILURE)
{
(void) fprintf (stderr, "Wrong airport coden");
}
}

return err;
}

/*********************************************************************

NAME : checktime ( *string, input_size )

USAGE : Check if the user entered a valid time.

PARAMETERS :
- Time entered by the user
- Input size

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int checktime (char *string, size_t input_size)
{
/* Exit status */
int err = EXIT_SUCCESS;

/* Time values : Hour and minutes */
unsigned short int time[2] {0, 0};

/* Debug : We check if the pointer is valid */
#ifdef DEBUG
if (string == NULL)
{
(void) fprintf (stderr, "Invalid string pointer.n");
err = EXIT_FAILURE;
}

/* Debug : We check if the input_size is correct
It must be 7 ( xx:xxn ) */
else if (input_size != 7)
{
(void) fprintf (stderr, "Input under/oversized. Must be 7.n");
err = EXIT_FAILURE;
}
#endif /* DEBUG */

/* We get the time */
err = get_answer (string, input_size);

/* We verify if the user put the separator */
if (string[2] != ':')
{
(void) puts ("Wrong separator or not placed correctly");
err = EXIT_FAILURE;
}

/* We check if the user doesn't enter a letter at the end */
else if (isdigit (string[4]) == 0)
{
(void) puts ("Wrong values");
err = EXIT_FAILURE;
}

/* We check if the user entered two numbers */
else if (sscanf (string, "%02hu:%02hu", &time[0], &time[1]) != 2)
{
(void) puts ("Wrong values");
err = EXIT_FAILURE;
}

/* Are the time values correct ? */
else if ((time[0] > 23) || (time[1] > 59))
{
(void) puts ("Wrong time, the maximal value for the hour is 23");
err = EXIT_FAILURE;
}

return err;
}

/*********************************************************************

NAME : ask ( *client_fl )

USAGE : Take the principal informations about the flight and do
some basic check.

PARAMETER : The client reservation data structure.

RETURNS (int) :
- EXIT_SUCCESS
- EXIT_FAILURE

*********************************************************************/

static int ask (reservation * client_fl)
{
/* Error status */
int err = EXIT_SUCCESS;

assert (client_fl != NULL); /* -ed- : l'un des deux tests est inutile */

/* We check if the pointer points to something useful */
if (client_fl == NULL)
{
(void) fprintf (stderr, "Data structure pointer client_fl is invalid
");
err = EXIT_FAILURE;
}

/* If everything is ok, we ask the first question */
else
{
(void) puts ("What's the starting airport code :");

err = checkcode (client_fl->orig_air_code,
sizeof (client_fl->orig_air_code));
}

/* Ok ? Next question */
if (err == EXIT_SUCCESS)
{
(void) puts ("What's the destination airport code :");

err = checkcode (client_fl->dest_air_code, sizeof (client_fl-
dest_air_code));
}


/* The flight number */
if (err == EXIT_SUCCESS)
{
(void) puts ("What's your flight number :");

err = get_answer (client_fl->flight_nb, sizeof (client_fl->flight_nb));
}

/* Starting and arrival time */
if (err == EXIT_SUCCESS)
{
(void) puts ("The flight will start at: ( Valid times are 00:00 ->
23:59) ");
err = checktime (client_fl->start_time, sizeof (client_fl-
start_time));
}


if (err == EXIT_SUCCESS)
{
(void) puts ("The plane will arrive at: ( Valid times are 00:00 ->
23:59) ");
err = checktime (client_fl->end_time, sizeof (client_fl->end_time));
}

/* If everything is ok, we print the user's flight information */
if (err == EXIT_SUCCESS)
{
(void) printf ("You start from | %sn"
"You'll fly to | %sn"
"Your flight number is | %sn"
"The plane will lift off at | %sn"
"The plane will arrive at | %sn",
client_fl->orig_air_code,
client_fl->dest_air_code,
client_fl->flight_nb,
client_fl->start_time,
client_fl->end_time);
}

return err;
}

/*********************************************************************

NAME : aircodes ( void )

USAGE : Display program version and airport codes.

*********************************************************************/

static void aircodes (void)
{
(void) puts ("Flight reservation v0.1");
(void) puts ("---------------------------------------------------------");
(void) puts ("Airport codes :");
(void) printf ("nJPU - Paris La Defensen"
"NYC - New York Multiple City Coden"
"TYO - Tokyo Naritan"
"TXL - Berlin Tegeln"
"LCY - London Cityn"
"HKG - Hong Kong Intln");
(void) puts ("---------------------------------------------------------
n");
}

int main (void)
{
/* Final exit status */
int err = EXIT_SUCCESS;

/* The data structure which contains client flight informations */
reservation client_fl {
{
0
}
,
{
0
}
,
{
0
}
,
{
0
}
,
{
0
}
};

/* Display the airport codes */
aircodes ();

/* Get the client flight informations */
(void) puts ("Welcome.");

err = ask (&client_fl);

return err;
}


--
-ed- [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/

Avatar
Emmanuel Delahaye
In 'fr.comp.lang.c', Eddahbi Karim
wrote:

Bonjour à tous,

J'suis rentré de vacanes et me revoici avec mes exos de C. Cette fois ci
crée une structure pour stocker les informations d'un vol.

Si vous avez tout commentaire sur le code, de manière à l'améliorer,
faites en part :-).


A propose de gestionnaire de vols, ce petit exercice devrait t'amuser:

#include <stdio.h>
#include <math.h>

#define NELEM(a) (sizeof(a)/sizeof*(a))
#define PI 3.14156

typedef struct
{
char name[4];
double longitude;
double latitude;
}
pos_s;

static const pos_s aeroports[] {
/* *INDENT-OFF* */
{"CDG", 48.867, 2.333},
{"DUB", 53.333, -6.250},
{"NYC", 40.714, -74.006},
{"NAR", 35.783, 140.317},
{"CAP", -33.917, 18.417},
{"RDJ", -22.900, -43.233},
/* *INDENT-ON* */

};

double deg2rad (double deg)
{
return 2 * PI * deg / 360;
}

/*
Formule de calcul de distance par orthonormie.

Ortho(A,B) = 6366
x acos(
cos(LatA)
x cos(LatB)
x cos(LongB - LongA)
+
sin(LatA)
x sin(LatB)
)

Nota : j'ai trouve cette formule sur un site. Je me contente de l'appliquer
betement.

*/
double dist_ortho (double LatA
,double LongA
,double LatB
,double LongB
)
{
return 6366 /* rayon moyen de la terre */
* acos (
cos (LatA)
* cos (LatB)
* cos (LongB - LongA)
+
sin (LatA)
* sin (LatB)
);
}

int main (void)
{
size_t i;

/* coordonnees */
for (i = 0; i < NELEM (aeroports); i++)
{
pos_s const *p = aeroports + i;

printf ("%s %6.2f?, %6.2f?n"
,p->name
,p->longitude
,p->latitude
);
}

/* distances */
for (i = 0; i < NELEM (aeroports); i++)
{
pos_s const *pi = aeroports + i;
size_t j;

for (j = 0; j < i; j++)
{
pos_s const *pj = aeroports + j;

if (i != j)
{
double dist = dist_ortho (deg2rad (pi->longitude)
,deg2rad (pi->latitude)
,deg2rad (pj->longitude)
,deg2rad (pj->latitude)
);

printf ("%s %s %.0f kmn"
,pi->name
,pj->name
,dist
);
}
}
}
return 0;
}

Pour avoir les coordonnées d'une ville dans le monde :

http://www.heavens-above.com/countries.asp

--
-ed- [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/

Avatar
Laurent Wacrenier
Eddahbi Karim écrit:
- flight_nb[6] : The flight number ( 4 digits max )
- orig_air_code[5] : The origin airport code ( 3 letters )
- dest_air_code[5] : The destination airport code ( 3 letters )
- start_time[7] : Starting time [2 digits : 2 digits]
- end_time[7] : Arrival time [2 digits : 2 digits]

*********************************************************************/

typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;


Il y a un caractère de trop à chaque fois. On peut aussi écrire :
char flight_nb[sizeof("1234")];
char orig_air_code[sizeof("ABC")];
char dest_air_code[sizeof("ABC")];
char start_time[sizeof("12:34")];
char end_time[sizeof("12:34")];

Ça évite de faire le calcul.


/* If nothing is wrong, grab the user value */ if ( err = > EXIT_SUCCESS )


Les commentaires avant le code, c'est pas très lisible.

Avatar
Yves ROMAN

Eddahbi Karim écrit:

typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;


Il y a un caractère de trop à chaque fois. On peut aussi écrire :
char flight_nb[sizeof("1234")];
char orig_air_code[sizeof("ABC")];
char dest_air_code[sizeof("ABC")];
char start_time[sizeof("12:34")];
char end_time[sizeof("12:34")];

Ça évite de faire le calcul.



est-ce que sizeof("12:34") ne donne pas
sizeof(char *)
au lieu de
sizeof(char[5+1])
?


Avatar
Laurent Wacrenier
Yves ROMAN écrit:
est-ce que sizeof("12:34") ne donne pas
sizeof(char *)
au lieu de
sizeof(char[5+1])
?


Non.

Avatar
Bertrand Mollinier Toublet
Eddahbi Karim wrote:

Bonjour à tous,

J'suis rentré de vacanes et me revoici avec mes exos de C. Cette fois ci
crée une structure pour stocker les informations d'un vol.

Si vous avez tout commentaire sur le code, de manière à l'améliorer,
faites en part :-).


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

/*--------------------------------------------------------------------

USAGE : Calculate the first dimension of a two dimensions array

PARAMETER : Two dimensional array

--------------------------------------------------------------------*/

#define FIRST_DIM_SIZE(array) sizeof((array)) / sizeof((array[0]))

C'est bien entendu une question de point de vue, mais il me semble que

cette expression est suffisament idiomatique et concise pour etre
utilisee telle quelle dans ton code. En particulier, ca evite les
problemes eventuels de double evaluation de ton argument...


typedef struct {
char flight_nb[6];
char orig_air_code[5];
char dest_air_code[5];
char start_time[7];
char end_time[7];
} reservation;

Pour repondre ici a ta question sur pourquoi ne pas stocker les 'n': il

s'agit d'une question de clarte et d'homogeneite du code. Un code
aeroport, c'est trois lettres. Pas trois lettres et un retour chariot.
Que ta fonction d'input te le file avec un retour chariot ne doit pas
avoir d'incidence sur ce que tu stockes.

/*********************************************************************

NAME : wipestring( string )

USAGE : Wipe useless values from the string...

PARAMETERS : char const *string to wipe...

*********************************************************************/

static void
wipestring (char const *string)
{
/* We search a 'n' character */
char *p = strchr (string, 'n');

/* We found it, we replace it by '' */ if (p)
{
*p = '';
}

/* We don't find it, so we get everything pending in stdin */ else
{
int c;

while ((c = getchar ()) != 'n' && c != EOF) {
}
}
}
Je suis surpris que personne n'ait fait de remarque a propos de cette

fonction. Tu prends une chaine de caracteres, string, et tu la modifies
probablement (dans le cas ou p est non nul). Dans ces conditions, c'est
conceptuellement maladroit (pour ne pas dire incorrect) d'indiquer ton
parametre comme etant de type const char *.

En plus la fonction est plutot mal foutue, si tu veux mon avis. D'un
cote tu modifie ton argument (a priori declare non modifiable), de
l'autre, tu fais une operation completement sans rapport (vider stdin).

Ce probleme de caracteres qui se baladent sur stdin qui t'embete est
aisement resolu par l'utilisation d'une fonction comme ggets, que
j'utilise pour la plupart de mes inputs, avec grande satisfaction, et
que je te recommande: http://cbfalconer.home.att.net/download/. Caveat
emptor: le seul truc auquel il faut faire attention, c'est de bien
liberer la chaine retournee par ggets, parce qu'elle est allouee
dynamiquement...

int main ( void )
{
/* Final exit status */
int err = EXIT_SUCCESS;

/* The data structure which contains client flight informations */
reservation client_fl = {{0}, {0}, {0}, {0}, {0}};


Qu'est ce qui ne va pas avec:
reservation client_fl = {0};
?


/* Display the airport codes */
aircodes();

/* Get the client flight informations */ (void) puts("Welcome.");

err = ask( &client_fl );

return err;
}



--
Bertrand Mollinier Toublet
Currently looking for employment in the San Francisco Bay Area
http://www.bmt.dnsalias.org/employment

Avatar
Emmanuel Delahaye
In 'fr.comp.lang.c', Yves ROMAN wrote:

est-ce que sizeof("12:34") ne donne pas
sizeof(char *)


Non. Aucun pointeur n'a été défini...

au lieu de
sizeof(char[5+1])


... Par contre un tableau de char l'a été, et c'est sa taille que voit le
sizeof.

--
-ed- [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/

1 2 3 4 5