Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generate a birthday date randomly in c

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 !

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading