现有两个不同的char型变量,取值为年月(yyyymm),要写一个循环取出他们之间的取值,例如:char1 = ‘201

1个回答

  • 基本上是用C写的,子函数改下try..catch那部分,就可以用C编译了.

    生成的字符串是用空格分开的,单个使用的话用strtok就行了.

    #include

    #include

    #include

    using namespace std;

    char* getInnerDate(char *char1,char *char2)

    {

    char *p1,*p2,*sRet,*pRet;

    int yy1,mm1,yy2,mm2,mm,m,y;

    char buff[10];

    // Swap date string order.

    if( strcmp(char2,char1) >= 0){

    p1 = char1;

    p2 = char2;

    }else{

    p1 = char2;

    p2 = char1;

    }

    // Translate to year & month.

    try{

    strncpy(buff,p1,6);

    buff[6] = 0;

    mm1 = atoi(&buff[4]);

    buff[4] = 0;

    yy1 = atoi(buff);

    strncpy(buff,p2,6);

    buff[6] = 0;

    mm2 = atoi(&buff[4]);

    buff[4] = 0;

    yy2 = atoi(buff);

    }catch(...){

    return NULL;

    }

    // Total months between 2 date strings.

    mm2 += (yy2 - yy1) * 12 + 1;

    sRet = (char*)malloc((mm2*7 + 1)*sizeof(char));

    if(NULL != sRet){

    pRet = sRet;

    y = yy1;

    m = mm1;

    for(int mm=mm1; mm 12){

    m -= 12;

    y ++;

    }

    sprintf(pRet,"%04d%02d ",y,m);

    m++;

    pRet += 7;

    }

    }

    return sRet;

    }

    int main(void)

    {

    char char1[]="201110",char2[]="201203";

    char *p;

    if(NULL != (p = getInnerDate(char1,char2))){

    cout