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

char *datestr = (char*)malloc(sizeof(char)*size);
  • date_create创建一个数据结构datestr
  • datestr预计格式为“dd/mm/yyyy”

基本上我在创建部分有一些问题我需要一些帮助来创建让我们说输入 02/11/2013 然后这个数据将被添加到指针中然后我必须以块的形式显示它们例如 02日期,11 月和 2013 年......有什么想法可以从这里继续吗?我将不得不使用 malloc 函数?

4

3 回答 3

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
于 2013-10-14T07:35:10.180 回答
0

也许是这样的

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;
}  
于 2013-10-14T07:54:53.407 回答
0

试试这个,并试着弄清楚它对你的书做了什么:

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;
}
于 2013-10-14T07:54:54.813 回答