Dennis
Dennis

Reputation: 186

How to extract a number from a string in C

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?

Upvotes: 3

Views: 8159

Answers (6)

chux
chux

Reputation: 153457

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

Upvotes: 0

Zied R.
Zied R.

Reputation: 4964

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

Upvotes: 1

barak manos
barak manos

Reputation: 30136

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

Upvotes: 2

LearningC
LearningC

Reputation: 3162

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

Upvotes: 0

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

char date[]="20-02-2015";
int d,m,y;
sscanf(date,"%d-%d-%d",&d,&m,&y);

Upvotes: 14

abligh
abligh

Reputation: 25129

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

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

Upvotes: 0

Related Questions