-2
Date *date_create(char *datestr);  
struct datestr { 
    int date; 
    int month; 
    int year;  
} 

char *datestr = (char*)malloc(sizeof(char)*size);
  • date_create creates a data structure from datestr
  • datestr is expected to be of the form "dd/mm/yyyy"

Basically I'm having some problems with the create portion i need some help in creating let's say an input 02/11/2013 and then this data will be added into the pointer and then i have to display them in terms of blocks such as 02 for date, 11 for month and 2013 for year... any ideas how to continue from here? i will have to use a malloc function?

Haris
  • 12,120
  • 6
  • 43
  • 70

3 Answers3

0
  • Use strtok and the atoi/strtol family to extract your integer values from the string
  • Alternatively you can use scanf to do this

  • Use malloc to allocate a struct of your type and fill the fields with the extracted values

  • Return the allocated pointer to your struct
LostBoy
  • 948
  • 2
  • 9
  • 21
0

maybe something like this

typedef struct 
{ 
    int day; 
    int month; 
    int year;  
} 
datestructure;

datestructure date_create(const char *datestr)
{
  datestructure ret; // return value
  char* datestrDup = strdup(datestr); // alloc/copy

  ret.day = strtok(datestrDup,"/"); 
  ret.month = strtok(NULL,"/");
  ret.year = strtok(NULL," ");

  free(datestrDup);
  return ret;
}  
AndersK
  • 35,813
  • 6
  • 60
  • 86
0

Try this, and try to work out what it's doing with your book:

typedef struct _dates
{ 
   int date; 
   int month; 
   int year;
} DateStr;

DateStr * date_create(char *datestr);

int main(int argc, char* argv[])
{
   DateStr *result;
   char inputString[100];
   printf("Enter the date: ");

    if (gets(inputString))
    {
        result = date_create(inputString);

        if (result)
        {
            printf("Parsed date is Date:%d, Month:%d, Year:%d",result->date, result->month, result->year);
        }
    }

    return 0;
} 


DateStr * date_create(char *datestr)
{
    DateStr * date = (DateStr *)malloc(sizeof(DateStr));

    if (date)
    {
        sscanf(datestr, "%d/%d%/%d",&date->date, &date->month, &date->year);
    }

    return date;
}
Baldrick
  • 11,712
  • 2
  • 31
  • 35