C语言 c语言中日期为dd/mm/yy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28744407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
taking date as dd/mm/yy in c language
提问by CuriousDeveloper
# include <stdio.h>
int main(){
int d1, d2, m1, m2, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d,%d/%d,&,d/%d", &d1,&d2,&m1,&m2,&year);
**Hello guys I am new in c programming so I'm trying to take the date as dd/mm/yy format but when I write it like this it gives me an output as 191/033/0 for 19/07/14 input how can i fix this? **
**大家好,我是 c 编程新手,所以我试图将日期设为 dd/mm/yy 格式,但是当我这样写时,它给了我 19/07/14 的输出为 191/033/0输入我该如何解决这个问题?**
回答by ForceBru
# include <stdio.h>
int main(){
int d, m, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d/%d/%d", &d,&m,&year);
if (d%10==1 && d!=11) printf("%d st",d);
else if (d%10==2 && d!=12) printf("%d nd",d);
else if (d%10==3 && d!=13) printf("%d rd",d);
else printf("%d th",d);
return 0;
}
By the way, dd/mm/yydoes notmean 'two days, two months and two years'. This means 'two digits for day, month and year'. That's why you don't need so many variables.
顺便说一句,dd/mm/yy并不意味着“两天、两个月和两年”。这意味着“日、月和年的两位数”。这就是为什么你不需要这么多变量。
回答by Iharob Al Asimi
You need the strftime()function, and handle the input correctly so nothing unexpected happens
您需要该strftime()功能,并正确处理输入,以免发生意外
This is an example of how to do it
这是一个如何做到的例子
#include <stdio.h>
#include <time.h>
#include <string.h>
int main()
{
char buffer[100];
struct tm date;
memset(&date, 0, sizeof(date));
printf("Enter date (dd/mm/yy): ");
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
return -1;
if (sscanf(buffer, "%d/%d/%d", &date.tm_mday, &date.tm_mon, &date.tm_year) == 3)
{
const char *format;
format = "Dated %A %dth of %B, %Y";
if (strftime(buffer, sizeof(buffer), format, &date) > sizeof(buffer))
fprintf(stderr, "there was a problem converting the string\n");
else
fprintf(stdout, "%s\n", buffer);
}
return 0;
}

