简体   繁体   中英

how to take a birth date format as a input with string in c programming

what is the best away to take a date format as input .like this.. dd/mm/yyyy. i do not like to use scanf("%d/%d/%d.........);

Your question is not very clear.
If you want to know how to take date input using scanf , here is how it is done.

int d,m,y;                   //This is your code.
scanf("%d/%d/%d",&d,&m,&y);  //Now this tells that scanf expect input in this format.

If you give input 23/4/12 , This will store 23 in d , 4 in m and 12 in y .

Never Take input using gets() and scanf() as they does not check buffer overflow , and gets() has been removed from the standard way long back. It is a well known security risk.

Instead use fgets () .Note fgets() also stores the ending new line character, to remove it I have used the following method below.

To take this input using fgets() .

#include <stdio.h>
int main(){

         char date[10];

         fgets(date,10,stdin);

         int i = 0;
         //Now For Removing new line character from end of the string.
         while(date[i]!='\0'){     

             if(date[i]=='\n'){
                        date[i] = '\0';
                        break;
                      }

            i++;
         }

         }

First of all you should avoid gets() to prevent buffer overflow.

Instead use the safest fgets()

char *fgets(char *s, int size, FILE *stream)

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\\0aq) is stored after the last character in the buffer.

Then you can use int sscanf(const char *str, const char *format, ...); which

reads its input from the character string pointed to by str.

Here is an example program :

#include <stdio.h>
#define MAXLEN 10

int main(int argc, char **argv)
{
    char date_of_birth[MAXLEN];
    int day_of_birth, month_of_birth, year_of_birth;

    fgets(date_of_birth, MAXLEN, stdin);
    
    sscanf(date_of_birth,"%d %*c %d %*c %d", &day_of_birth, &month_of_birth, &year_of_birth);
    
    printf("\nDay of birth : %d\nMonth of birth : %d\nYear of birth : %d\n", day_of_birth, month_of_birth, year_of_birth);

    return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM