Search code examples
cinputc-stringsstring-parsing

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.........);


Solution

  • 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;
    
    }