如何在C中创建一个输入出生日期的函数。

huangapple go评论57阅读模式
英文:

how to create function to input date of birth in C

问题

你想要创建一个能够将用户的出生日期输入到结构体 char DateBirth[10]; 中,并以DD/MM/YYYY的格式显示的代码。以下是你的代码,已经添加了日期输入和格式化输出的部分:

#include <stdio.h>

// create a struct to store users information
struct user
{
    int ID;
    char Username[50];
    char DateBirth[10]; // Changed the size to 10 for DD/MM/YYYY format
    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: ");
    getchar(); // Consume the newline character left in the buffer
    gets(u.Class);
    printf("\nDate: ");
    scanf("%d", &Date);
    printf("\nMonth: ");
    scanf("%d", &Month);
    printf("\nYear: ");
    scanf("%d", &Year);

    // Format the Date of Birth as DD/MM/YYYY and store it in the struct
    sprintf(u.DateBirth, "%02d/%02d/%04d", Date, Month, Year);

    return 0;
}

这个代码会接受用户的日期输入,将其格式化为DD/MM/YYYY,并存储在 DateBirth 字段中。

英文:
#include &lt;stdio.h&gt;

// 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(&quot;\nName:&quot;);
    gets(u.Username);
    printf(&quot;\nID: &quot;);
    scanf(&quot;%d&quot;,&amp;u.ID);
    printf(&quot;\nClass: &quot;);
    gets(u.Class);
    printf(&quot;\nDate: &quot;);
    scanf(&quot;%d&quot;,&amp;Date);
    printf(&quot;\nMonth: &quot;);
    scanf(&quot;%d&quot;,&amp;Month);
    printf(&quot;\nYear: &quot;);
    scanf(&quot;%d&quot;,&amp;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.

答案1

得分: 0

scanf("%d", ... 未消耗Enter'\n'之后的数字文本,因此后续的gets()fgets()只会读取"\n"

scanf("%d", &u.ID);
...
gets(u.Class);  // 仅获取"\n"

替代方法

考虑使用fgets()来获取所有用户输入的字符串,然后解析字符串以获取ID、Class等信息。

请注意,自C11以来,gets()不再是标准C库的一部分。如果您的源材料建议使用gets(),则应该寻找更新的材料。

英文:

Problem code

scanf(&quot;%d&quot;, ... does not consume the <KBD>Enter></KBD> or &#39;\n&#39; after the number text and so a following gets() or fgets() will only read &quot;\n&quot;.

scanf(&quot;%d&quot;,&amp;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.

huangapple
  • 本文由 发表于 2023年4月19日 22:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定