英文:
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 <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.
答案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("%d", ...
does not consume the <KBD>Enter></KBD> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论