c++ 可变参数的使用

实例:

int DealMessageLog(char * argu, ...)
{
   va_list args;
  va_start(args,argu);

  int iBufferLen=0;
  char * pBufferHead=NULL;
  char * pTempBufferHead=NULL;
  char cBufferTemp[256]={0};
  char cBuffer[1024]={0};
  strcpy(cBufferTemp, argu);
  pBufferHead=cBuffer;
  pTempBufferHead=cBufferTemp;

  while(true)
  {
   char * p = strchr(pTempBufferHead,'%');

   if( NULL!=p )
   {
    p++;
    int iLength=(int)(p-pTempBufferHead)-1;
    if((iBufferLen+iLength)>1024)
    return -1;
    memcpy(pBufferHead,pTempBufferHead,iLength);
    pBufferHead+=iLength;
    iBufferLen+=iLength;
    pTempBufferHead+=iLength+1;
   
    if( *p!='/0')
    {
     if( *p == 'd' )
     {
      char itemp[64]={0};
      int iParam = va_arg(args,int);
      sprintf(itemp,"%d",iParam);
      int iLength=(int)strlen(itemp);
      if((iBufferLen+iLength)>1024)
      return -1;
      memcpy(pBufferHead,itemp,iLength);
      pBufferHead+=iLength;
      iBufferLen+=iLength;
     }
     else if( *p == 'f' )
     {
      char itemp[64]={0};
      double fParam = va_arg(args,double);
      sprintf(itemp,"%f",fParam);
      int iLength=(int)strlen(itemp);
      if((iBufferLen+iLength)>1024)
      return -1;
      memcpy(pBufferHead,itemp,iLength);
      pBufferHead+=iLength;
      iBufferLen+=iLength;
     }
     else
     {
      char * cPItem = va_arg(args,char *);
      int iLength=(int)strlen(cPItem);
      memcpy(pBufferHead,cPItem,iLength);
      if((iBufferLen+iLength)>1024)
      return -1;
      pBufferHead+=iLength;
      iBufferLen+=iLength;
     }
     p++;
     pTempBufferHead++;
    }

   }
   else
   {
    int iLength=(int)strlen(cBufferTemp)-(int)(pTempBufferHead-cBufferTemp);
    memcpy(pBufferHead,pTempBufferHead,iLength);
    pBufferHead+=iLength;
    break;
   }
  }

   va_end(args);
  printf("%s/n",cBuffer);


 return -1;
}

 

上述代码实现把可变参数转换成一个字符串

字符串就可以做你相应的处理;可以存成文件或打印输出

你可能感兴趣的:(c++ 可变参数的使用)