469,914 Members | 2,453 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,914 developers. It's quick & easy.

Extracting data from a date

I have a program that gets a date from the user in the format dd/mm/yy, and
I need to extract the d's, m's, and y's to be used within the program. I
have the program get the date as a string. How can I get the days, month,
and year numbers out of it?
Sep 25 '05 #1
2 2719
deanfamily11 wrote:
I have a program that gets a date from the user in the format dd/mm/yy, and
I need to extract the d's, m's, and y's to be used within the program. I
have the program get the date as a string. How can I get the days, month,
and year numbers out of it?


Use a stringstream, which lets you read from a string just like any
other stream.

#include <sstream>

std::istringstream buffer(date);
int day, mth, yr;
char slash1, slash2;
buffer >> day >> slash1 >> mth >> slash2 >> yr;

No error checking here of course, but that would probably be easier to
do on string than the stringstream.

john
Sep 25 '05 #2

deanfamily11 wrote:
I have a program that gets a date from the user in the format dd/mm/yy, and
I need to extract the d's, m's, and y's to be used within the program. I
have the program get the date as a string. How can I get the days, month,
and year numbers out of it?


You may use sscanf() for string parsing.

#include <stdio.h>

struct date
{
unsigned short year, month, day;
};

int str_to_date(char const* s, date* d)
{
return 3 == sscanf(s, "%2hu/%2hu/%4hu", &d->day, &d->month,
&d->year)
? 0
: -1
;
}

int main(int ac, char** av)
{
date d;
if(str_to_date(av[1], &d))
printf("bad date format\n");
else
printf("date: %02hu/%02hu/%04hu\n", d.day, d.month, d.year);
}

Sep 26 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by jerryyang_la1 | last post: by
2 posts views Thread by robinsiebler | last post: by
4 posts views Thread by dexter48 | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.