以日期格式作为输入.like的最佳方式是什么?dd/mm/yyyy我不喜欢使用扫描器(“%d/%d/%d.”);
发布于 2017-01-26 12:10:17
首先,您应该避免gets()
,以防止缓冲区溢出。
而是使用最安全的fgets()
char *fgets(char *s, int size, FILE *stream)
fgets()
从流中读取最多小于大小的字符,并将它们存储到由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;
}
发布于 2017-01-26 11:20:27
你的问题不太清楚。
如果您想知道如何使用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
,这将将23
存储在d
中,4
存储在m
中,12
存储在y
中。
不要使用gets()
和scanf()
进行输入,因为它们不检查缓冲区溢出,而且gets()
已经从标准方式中删除很久了。这是众所周知的安全风险。
相反,使用fget()
.Note 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++;
}
}
https://stackoverflow.com/questions/41876023
复制相似问题