I am working on a project for school but I can't figure out how I can extract the year from a date in a string "20-02-2015"
the date is always of the form XX-XX-XXXX
Is there some way to use some kind of scan function?
I am working on a project for school but I can't figure out how I can extract the year from a date in a string "20-02-2015"
the date is always of the form XX-XX-XXXX
Is there some way to use some kind of scan function?
char date[]="20-02-2015";
int d,m,y;
sscanf(date,"%d-%d-%d",&d,&m,&y);
Assuming that your string is given as char* str
or as char str[]
, you can try this:
int day,mon,year;
sscanf(str,"%d-%d-%d",&day,&mon,&year);
Or you can try this, for a slightly better performance (by avoiding the call to sscanf
):
int year = 1000*(str[6]-'0')+100*(str[7]-'0')+10*(str[8]-'0')+(str[9]-'0');
You can use the strtok() function to split a string (and specify the delimiter to use)
#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;
}
the output :
01
03
2014
Yes, with the %d-%d-%d
format.
If reading from STDIN, use scanf
, from a file use fscanf
and from a string use sscanf
you can divide the string using strtok(date,"-") then can use atoi() to get the date, month and year as numbers. check this link it can help you
strtok
if number of tokens is known and small.
Mar 1, 2014 at 16:39
As other have suggested "%d-%d-%d"
.
To add error checking, should code need to insure no trailing garbage and all was there:
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();