我正在为学校做一个项目,但是我不知道如何从字符串"20-02-2015"
中提取年份,日期格式始终为XX-XX-XXXX
是否有一种使用扫描函数的方法?
我正在为学校做一个项目,但是我不知道如何从字符串"20-02-2015"
中提取年份,日期格式始终为XX-XX-XXXX
是否有一种使用扫描函数的方法?
char date[]="20-02-2015";
int d,m,y;
sscanf(date,"%d-%d-%d",&d,&m,&y);
char *str
或者 char str[]
的形式给出,你可以尝试以下方法:int day,mon,year;
sscanf(str,"%d-%d-%d",&day,&mon,&year);
或者你可以尝试这个方法,它会稍微提升一点性能(通过避免调用sscanf
函数):
int year = 1000*(str[6]-'0')+100*(str[7]-'0')+10*(str[8]-'0')+(str[9]-'0');
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *date = malloc(10);
char *day = NULL;
char *month = NULL;
char *year = NULL;
strcpy(date, "01-03-2014");
day = strtok(date, "-");
printf("%s\n",day);
month = strtok(NULL, "-");
printf("%s\n",month);
year = strtok(NULL, "-");
printf("%s\n",year);
free(date);
return 0;
}
输出:
01
03
2014
正如其他人建议的那样,使用"%d-%d-%d"
。
为了添加错误检查,代码需要确保没有尾随垃圾并且所有内容都在:
char date[80];
fgets(data, sizeof date, stdin);
int d,m,y;
in n;
int cnt = sscanf(date, "%d-%d-%d%n", &d, &m, &y, &n);
if (cnt == 3 && date[n] == '\n') Good();
else Bad();
是的,使用 %d-%d-%d
格式。
如果从 STDIN 读取,请使用 scanf
,从文件中使用 fscanf
,从字符串中使用 sscanf
strtok
。 - HelloWorld123456789