3

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?

1
  • I think my upvote will enable u to upvote @Rikayan answer:) Mar 1, 2014 at 16:56

6 Answers 6

12
char date[]="20-02-2015";
int d,m,y;
sscanf(date,"%d-%d-%d",&d,&m,&y);
2
  • 2
    Thank you that worked yes, if i had more then 15 reputation i would have upvoted you :)
    – Dennis
    Mar 1, 2014 at 16:48
  • @Dennis You will, later. Welcome to the site! Mar 1, 2014 at 16:49
2

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');
1

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
0

Yes, with the %d-%d-%d format.

If reading from STDIN, use scanf, from a file use fscanf and from a string use sscanf

1
  • But which scan function should i use then? Because i only know the scanf() to read keyboard input
    – Dennis
    Mar 1, 2014 at 16:36
0

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

2
  • No need to use strtok if number of tokens is known and small. Mar 1, 2014 at 16:39
  • @RikayanBandyopadhyay i told the possibilities in general. ya in this case since format is fixed can use sscanf() easily.
    – LearningC
    Mar 1, 2014 at 16:43
0

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.