1
#include <stdio.h>

// create a struct to store users information
struct  user
    {
        int ID;
        char Username[50];
        char DateBirth[50];
        char Class[10];
    };
int InputUser(){

    int n;
    int Date;
    int Month;
    int Year;
    user u;
    printf("\nName:");
    gets(u.Username);
    printf("\nID: ");
    scanf("%d",&u.ID);
    printf("\nClass: ");
    gets(u.Class);
    printf("\nDate: ");
    scanf("%d",&Date);
    printf("\nMonth: ");
    scanf("%d",&Month);
    printf("\nYear: ");
    scanf("%d",&Year);

    return 0;
}

I want to input Date of Birth from users into struct char DateBirth[10]; and it will display DD/MM/YYYY. Example: 19/04/2023. How can I create a code for Date of Birth ? My code is above.

Dinosour
  • 45
  • 3
  • 1
    `gets` is outdated since some 25 years back and was finally removed from the C language 12 years ago. The source of learning that told you to use it needs to be replaced with something up to date. – Lundin Apr 19 '23 at 14:19
  • first thing you need to do is make that `char DataBirth[11]` to leave room for the NUL terminator, and [stop using `gets`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used/4309845#4309845). Then, check out [sprintf](https://linux.die.net/man/3/sprintf) to write formatted data to a string. – yano Apr 19 '23 at 14:19
  • Don't try to mix calls to scanf and f/gets in the same program. It almost always leads to trouble. See also [these other guidelines](https://stackoverflow.com/questions/72178518#72178652) for using scanf safely. – Steve Summit Apr 19 '23 at 16:11

1 Answers1

0

Problem code

scanf("%d", ... does not consume the Enter> or '\n' after the number text and so a following gets() or fgets() will only read "\n".

scanf("%d",&u.ID);
...
gets(u.Class);  // Only gets `\n`

Alternative

Consider using fgets() for all user input into a string. Then parse the string for ID, Class, etc.

Note that gets() is no longer part of the standard C library since C11. If your source material suggest using gets(), you deserve newer material.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256