[英]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.