PDA

View Full Version : Extracting a date from a char string


guyndenton
09-21-2002, 01:24 AM
Sorry if this has been been asked, but I already did some research and couldn't find what I was looking for....

A little about what I'm needing to do.
Create a structure of type date that contains three members: the month, the day of the month, and the year, all of type int. (Or use day-month-year order if you prefer.) Have the user enter a date in the format 12/31/2001, store it in a variable of type struct date, then retrieve the values from the variable and print them out in the same format.

Here's my code thus far:

struct date
{
int DateMonth, DateDay, DateYear;
};

void main ()
{
char DateIn;

cerr << "Please enter a date in the format 12/01/2001: ";
cin >> DateIn;
cerr << endl;
}

I need to extract the integers from the char string into the repective fields in the struct employee. Once I extract the needed data, I just need to spit out what date in a similar format.

Thanks.

Strike
09-21-2002, 09:29 AM
This smells an awful lot like someone's homework to me.

kmj
09-21-2002, 10:56 AM
Originally posted by Strike
This smells an awful lot like someone's homework to me.

Agreed; I'll give you one hint. You can't manipulate a string of characters in a variable that is just a char. In fact, that cin will only read in one character.

El Paso
09-29-2002, 08:02 AM
Hmmmmmmm. Divide and conquer.

I would advise you check out the various C++ string-input functions.

Also, make subsequent functions to get the day, month, and year from the string.

skidooer
11-01-2002, 11:30 AM
Originally posted by guyndenton
struct date
{
int DateMonth, DateDay, DateYear;
};

void main ()
{
char DateIn;

cerr << "Please enter a date in the format 12/01/2001: ";
cin >> DateIn;
cerr << endl;
}
First off, you can't store more than one character in DateIn the way you have it.

struct date
{
int DateMonth, DateDay, DateYear;
};

void get_date(struct date *ds, char *date)
{
int pos[2];
int i =0, j = 0;

while(*(date + i))
{
if(*(date + i) == '/' && j < 2)
{
*(date + i) = '\0';
pos[j++] = i + 1;
}
i++;
}

ds->DateMonth = atoi(date);
ds->DateDay = atoi(date + pos[0]);
ds->DateYear = atoi(date + pos[1]);
}

int main()
{
char DateIn[11];
struct date d;

cerr << "Please enter a date in the format 12/01/2001: ";
cin >> DateIn;
cerr << endl;

get_date(&d, DateIn);

return 0;
}