[英]how to take a birth date format as a input with string in c programming
what is the best away to take a date format as input .like this.. dd/mm/yyyy.什么是最好的日期格式作为输入。像这样.. dd/mm/yyyy。 i do not like to use scanf("%d/%d/%d.........);
我不喜欢使用 scanf("%d/%d/%d.........);
Your question is not very clear.你的问题不是很清楚。
If you want to know how to take date input using scanf , here is how it is done.如果您想知道如何使用 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.
If you give input 23/4/12
, This will store 23
in d
, 4
in m
and 12
in y
.如果您输入
23/4/12
,这将在d
存储23
,在m
存储4
,在y
存储12
。
Never Take input using gets()
and scanf()
as they does not check buffer overflow , and gets()
has been removed from the standard way long back.永远不要使用
gets()
和scanf()
gets()
输入,因为它们不检查缓冲区溢出,而且gets()
已从很久以前的标准方式中删除。 It is a well known security risk.这是众所周知的安全风险。
Instead use fgets ()
.Note fgets()
also stores the ending new line character, to remove it I have used the following method below.而是使用 fgets
()
。注意fgets()
还存储结束的换行符,要删除它,我使用了下面的方法。
To take this input using 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++;
}
}
First of all you should avoid gets()
to prevent buffer overflow.首先,您应该避免
gets()
以防止缓冲区溢出。
Instead use the safest fgets()
而是使用最安全的
fgets()
char *fgets(char *s, int size, FILE *stream)
fgets()
reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.fgets()
从流中读取至多小于 size 的字符,并将它们存储到 s 指向的缓冲区中。 Reading stops after an EOF or a newline.阅读在 EOF 或换行符后停止。 If a newline is read, it is stored into the buffer.
如果读取换行符,则将其存储到缓冲区中。 A terminating null byte (aq\\0aq) is stored after the last character in the buffer.
终止空字节 (aq\\0aq) 存储在缓冲区中的最后一个字符之后。
Then you can use int sscanf(const char *str, const char *format, ...);
然后你可以使用
int sscanf(const char *str, const char *format, ...);
which哪一个
reads its input from the character string pointed to by str.
从 str 指向的字符串读取其输入。
Here is an example program :这是一个示例程序:
#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.