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 )
{
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);
}
/* 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");
}
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;
}
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 :");
/* 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);
}
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.");
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 ' ' */
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.
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
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 :-).
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 ' ' */
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.
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 }
} ;
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 ' ' */
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.
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
Eddahbi Karim
[...]
Je mettrais plutot: #define FIRST_DIM_SIZE(array) (sizeof(array) / sizeof((array)[0]))
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 ?
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 ?
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 ?
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; } } }
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); }
/* 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"); } }
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; }
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 :");
/* 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); }
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;
}
}
}
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);
}
/* 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");
}
}
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;
}
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 :");
/* 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);
}
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; } } }
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); }
/* 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"); } }
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; }
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 :");
/* 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); }
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;
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;
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;
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.
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.
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.
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]) ?
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])
?
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]) ?
Laurent Wacrenier
Yves ROMAN écrit:
est-ce que sizeof("12:34") ne donne pas sizeof(char *) au lieu de sizeof(char[5+1]) ?
Non.
Yves ROMAN <yves.roman@unilog.fr> écrit:
est-ce que sizeof("12:34") ne donne pas
sizeof(char *)
au lieu de
sizeof(char[5+1])
?
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...
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.
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
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 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...
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.
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
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...
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.
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
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/
In 'fr.comp.lang.c', Yves ROMAN <yves.roman@unilog.fr> 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- emdelYOURBRA@noos.fr [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/