OVH Cloud OVH Cloud

Meilleure façon de demander la date ?

39 réponses
Avatar
Eddahbi Karim
Bonjour, Bonsoir,

Voilà je continue les exercices de mon bouquin de C.
J'en suis au chapitre concernant les structures et ils demandent de créer
une structure contenant le temps et la date. (Puis de calculer l'espace
entre deux temps en minutes).

Ma question est :

Est-il mieux de demander à l'utilisateur de rentrer la date comme ceci :
- mm/jj/aaaa
Puis de prendre les valeurs mm et jj, avec un srtoi (C99) ou un strtod
(Ansi) quit à caster en int après, et de les vérifier. Ou
- mm jj aaaa
Puis de prendre après les valeurs à l'aide d'un sscanf(input,"%d %d %d",
...) pour les vérifier après.

Et pour le temps vous avez une idée ?
J'ai pensé que la méthode 88:88 serait pas mal mais si vous avez une autre
idée ;).

Merci,
Voila ;),
ThE_TemPLaR

9 réponses

1 2 3 4
Avatar
Eddahbi Karim

[snip]

Merci bien ;)
Avatar
Bertrand Mollinier Toublet
AG wrote:
C'est pour avoir une gestion d'erreur, or comme je ne peux renvoyer
qu'une
structure, j'ai mis la gestion d'erreur dans la structure, maintenant,
y'a
peut être un autre moyen, mais je ne vois pas lequel.



Souvent, les fonctions ont un pointeur en argument qui permet de remplir
une structure : ce sont les valeurs de retour de la fonction.
Par ailleurs, la fonction renvoie un int dont la valeur indique le
déroulement de l'opération :

exemple :

typedef struct complex_s
{
double a;
double b;
} complex_t;

int init_complex(complex_t * z)
{
if(z)
{
z->a=0;
z->b=0;
return 0;
}
else
{
fprintf(stderr,"invalid pointern");
return 1;
}
}

c'est comme cela que fonctionnent beaucoup de fonctions de la
biliothèque standard.

Oui.

et non.

Recement, je me suis mis d'accord avec moi-meme que j'allais avoir deux
types de fonctions dans mon code. Les fonctions de creations d'objets,
d'instanciation, si l'on veut, qui renvoient un pointeur sur l'objet
nouvellement cree, et les autres, qui le cas echeant modifient les
objets passes en argument, et renvoient un code d'erreur. Dans cette
optique, ta fonction d'exemple, je la place plutot dans ma premiere
categorie:

typedef struct complex_s
{
double r;
double i;
} complex_t;

complex_t *complex_create(void)
{
complex_t *new_c;

new_c = malloc(sizeof *new_c);
if (NULL != new_c)
{
new_c->r = 0;
new_c->i = 0;
}
return new_c;
}

... et la, je voulais ajouter un exemple de fonction qui modifierait un
complexe et renverrait un code d'erreur, et j'ai rien trouve :-(

Bref, c'etait juste pour prendre la tete, et faire remarquer que j'aime
bien la convention du "retourner NULL si la creation de l'objet echoue".
--
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', Bertrand Mollinier Toublet
wrote:

Recement, je me suis mis d'accord avec moi-meme que j'allais avoir deux
types de fonctions dans mon code. Les fonctions de creations d'objets,
d'instanciation, si l'on veut, qui renvoient un pointeur sur l'objet
nouvellement cree, et les autres, qui le cas echeant modifient les
objets passes en argument, et renvoient un code d'erreur.


<...>

Bref, c'etait juste pour prendre la tete, et faire remarquer que j'aime
bien la convention du "retourner NULL si la creation de l'objet echoue".


Tout à fait d'accord.

--
-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
EpSyLOn
On Fri, 25 Jul 2003 18:49:52 +0200, EpSyLOn
wrote:

[...]
Merde !
Cette fois c'est la bonne. Encore désolé.

--
.-. EpSyLOn sas<dot>epsylon<at>wanadoo<dot>fr
oo| faq fclc: http://www.isty-info.uvsq.fr/~rumeau/fclc
/`' Usenet : http://www.usenet-fr.net
(_;/) "Bus error - passengers dumped"
Avatar
Gabriel Dos Reis
EpSyLOn writes:
| >Et les deux documents en question ne parlent pas de la longueur
| >des signatures ?
|
| Sisi.
| Vala, c'est réglé

en es-tu sûr ?

-- Gaby
Avatar
Eddahbi Karim
Voilà,

Je pense l'avoir remanier dans le bon sens :).

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

/************************Structure************************************

NAME : date

CONTAINS :
- The input to insert the date
- The month, day and year taken from the input
- The error value to solve problem cases

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

typedef struct
{
char input[12];
unsigned short int month;
unsigned short int day;
unsigned short int year;
} date;

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

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 :
- 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)
{
printf ("Input Errorn");
err = EXIT_FAILURE;
}

/* Check if the user entered something */
else
{

if ( strchr(string, 'n') == NULL )
{
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 == '')
{
printf ("No inputn");
err = EXIT_FAILURE;
}

}
}

return err;
}

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

NAME : checkdate ( month, day, year )

PARAMETERS :
- unsigned short int day which will be check with the month and the
year
- unsigned short int month
- unsigned short int year

RETURNS :
- EXIT_SUCCESS if no problem.
- EXIT_FAILURE if there was a wrong value.

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

static int
checkdate ( unsigned short int month, unsigned short int day,
unsigned short int year)
{
/* The number of days in each month.
There's 13 values, because the first value is 0 and month 0
doesn't exist */
static unsigned short int days_in_month[13] = {
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};

/* The error value */
int err = EXIT_SUCCESS;

/* If the year is leap and the month is Februar */
if ( (month == 2)
&& (year % 4 == 0)
&& (( year % 100 != 100 ) || ( year % 400 == 0))
&& (( day < 1) || ( day > 29 ))
)
{
printf("Month or day invalid");
err = EXIT_FAILURE;
}

/* If the day or the month isn't valid at all, we don't continue */
else if ((day < 1 ) || (day > 31) || (month < 1) || (month > 12))
{
fprintf(stderr, "Month or day invalid.n");
err = EXIT_FAILURE;
}
/* If the day is superior to the max in the month entered */
else if ( day > days_in_month[month] )
{
(void) fprintf(stderr, "Day invalid according to the month.n");
err = EXIT_FAILURE;
}

return err;

}



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

NAME : takedate( *p_usertime )

PARAMETERS :
- Date structure

RETURN :
- Date structure

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


static int
takedate (date *p_userdate)
{
/* Error management */
int err = EXIT_SUCCESS;

/* Improve visibility with clear names */
unsigned short int month = p_userdate->month;
unsigned short int day = p_userdate->day;
unsigned short int year = p_userdate->year;

/* We check the pointer and the variables */
assert ( p_userdate != NULL
&& month == 0 && day == 0 && year == 0 );

/* If we point to nothing, stop */
if ( p_userdate == NULL )
{
printf("Invalid structure pointer.n");
err = EXIT_FAILURE;
}

else
{
(void) printf("Enter a date (mm/dd/yyyy) : ");
(void) fflush(stdout);

/* If nothing is wrong with the input itself, we check if the user
followed the instructions */
err = getstring( p_userdate->input, sizeof(p_userdate->input) );

if ( err == EXIT_SUCCESS )
{
if ( sscanf(p_userdate->input, "%02hu/%02hu/%04hu",
&month, &day, &year) != 3 )
{
(void) fprintf(stderr, "Invalid date or bad separator.n");
err = EXIT_FAILURE;
}
}

/* If nothing is wrong, check if the date is correct */
if ( err == EXIT_SUCCESS )
err = checkdate(month, day, year);

/* If the date is correct, we display it */
if ( err == EXIT_SUCCESS )
printf("You have entered : %s.n", p_userdate->input);

/* If everything was ok, we update the structure values */
if ( err == EXIT_SUCCESS )
{
p_userdate->month = month;
p_userdate->year = year;
p_userdate->day = day;
}
}

return err;
}

int
main (void)
{
/* Error management */
int err = EXIT_SUCCESS;

/* Index array */
int index = 0;

/* The initialisation of the array of structures
input, month, day, year, err */
date userdate[2] = {
{{0}, 0, 0, 0},
{{0}, 0, 0, 0}
};

for ( index = 0; index < 2 && err == EXIT_SUCCESS; index++ )
{
err = takedate( &userdate[index] );
}

return err;

}

Tiens en passant, serait il moins bien de faire comme ceci pour les
commentaires :

int main ( void )
{
/* This function does something, somewhere in the world */
function(args);

/* And this functions does another thing */
function2(args);

return 0;
}

Merci beaucoup ;),
Voila,
ThE_TemPLaR
Avatar
Laurent Wacrenier
Eddahbi Karim écrit:
&& (( year % 100 != 100 ) ||


Ça ne doit pas arriver souvent.

Avatar
Jean Claude Calvez
"Laurent Wacrenier" <lwa@ teaser . fr> a écrit dans le message news:

Eddahbi Karim écrit:
&& (( year % 100 != 100 ) ||


Ça ne doit pas arriver souvent.



Ce ne serait pas plutôt le contraire ?
% donne le reste d'une division entière, donc
year % 100 a pour résultat un entier compris
entre 0 et 99, bornes comprises, et donc
year % 100 != 100 est toujours vérifié.

--

Jean Claude Calvez



Avatar
Eddahbi Karim


"Laurent Wacrenier" <lwa@ teaser . fr> a écrit dans le message news:



[snip]

Mais qu'est ce je suis c...

C'est corrigé merci :).

Voila ;),
ThE_TemPLaR

1 2 3 4