int nombreAlea(int min, int max){
return (rand()%(max-min 1) min);
}
int main () {
srand(time(0));
int annee=nombreAlea(1940,2003),mois=nombreAlea(1,12),jour;
/// le traitement de la date
if((mois==1)||(mois==3)||(mois==5)||(mois==7)||(mois==8)||(mois==10)||(mois==12)) jour = nombreAlea(1,31);
if((mois==4)||(mois==6)||(mois==9)||(mois==11)) jour = nombreAlea(1,30);
if(mois==2)
{if (annee % 4 == 0 )
jour = nombreAlea(1,28);
else
jour = nombreAlea(1,29);
}
/// the format of the date is jj/mm/aaaa
signed char Date[20];
signed char jour_c[3],mois_c[3],annee_c[6];
itoa(jour,jour_c,10);
itoa(mois,mois_c,10);
itoa(annee,annee_c,10);
Date[0]=jour_c[0];
Date[1]=jour_c[1];Date[2]='/';
Date[3]=mois_c[0];Date[4]=mois_c[1];Date[5]='/';
Date[6]=annee_c[0];Date[7]=annee_c[1];Date[8]=annee_c[2];Date[9]=annee_c[3];Date[10]='\0';
printf("%s",Date);
return 0 ;
}
i want to generate a birthday day randomly , but the problem is that sometimes i get the half of the date , and smetimes i get only 2 caracters , and i don't understand where s the problem , any help !
CodePudding user response:
As Barmar's comment, you can't assume that jour_c
and mois_c
are one-character strings. Use
Date[0] = '\0'; // or you can initialize it as signed char Date[20] = {0};
strcat(Date, jour_c);
strcat(Date, "/");
strcat(Date, mois_c);
strcat(Date, "/");
strcat(Date, annee_c);
instead of
Date[0]=jour_c[0];
Date[1]=jour_c[1];Date[2]='/';
Date[3]=mois_c[0];Date[4]=mois_c[1];Date[5]='/';
Date[6]=annee_c[0];Date[7]=annee_c[1];Date[8]=annee_c[2];Date[9]=annee_c[3];Date[10]='\0';
CodePudding user response:
The problem is that
jour_c
will only be 1 digit for days between 1 and 9, sojour_c[1]
will be the null terminator, not the second digit.
– Barmar