[英]how to take a birth date format as a input with string in c programming
什么是最好的日期格式作为输入。像这样.. dd/mm/yyyy。 我不喜欢使用 scanf("%d/%d/%d.........);
你的问题不是很清楚。
如果您想知道如何使用 scanf 进行日期输入,这里是如何完成的。
int d,m,y; //This is your code.
scanf("%d/%d/%d",&d,&m,&y); //Now this tells that scanf expect input in this format.
如果您输入23/4/12
,这将在d
存储23
,在m
存储4
,在y
存储12
。
永远不要使用gets()
和scanf()
gets()
输入,因为它们不检查缓冲区溢出,而且gets()
已从很久以前的标准方式中删除。 这是众所周知的安全风险。
而是使用 fgets ()
。注意fgets()
还存储结束的换行符,要删除它,我使用了下面的方法。
使用fgets()
获取此输入。
#include <stdio.h>
int main(){
char date[10];
fgets(date,10,stdin);
int i = 0;
//Now For Removing new line character from end of the string.
while(date[i]!='\0'){
if(date[i]=='\n'){
date[i] = '\0';
break;
}
i++;
}
}
首先,您应该避免gets()
以防止缓冲区溢出。
而是使用最安全的fgets()
char *fgets(char *s, int size, FILE *stream)
fgets()
从流中读取至多小于 size 的字符,并将它们存储到 s 指向的缓冲区中。 阅读在 EOF 或换行符后停止。 如果读取换行符,则将其存储到缓冲区中。 终止空字节 (aq\\0aq) 存储在缓冲区中的最后一个字符之后。
然后你可以使用int sscanf(const char *str, const char *format, ...);
哪一个
从 str 指向的字符串读取其输入。
这是一个示例程序:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.