format:自己写的format函数

来源:互联网 发布:macbook专业修图软件 编辑:程序博客网 时间:2024/09/21 09:00

重载自string类,实现额外的Format功能

 void Format(const char* szFmt, ...)
  {
   va_list argList;
   va_start(argList, szFmt);
   FormatV(szFmt, argList);
   va_end(argList);
  }

 

void FormatV(const char* szFormat, va_list argList)
  {
   char* pBuf = NULL;
   int nChars = 1;
   int nUsed = 0;
   size_type nActual = 0;
   int nTry = 0;
   
   do
   {
    // Grow more than linearly (e.g. 512, 1536, 3072, etc)
    nChars += ((nTry+1) * FMT_BLOCK_SIZE);
    pBuf = reinterpret_cast<char*>(_alloca(sizeof(char)*nChars));
    nUsed = ::_vsnprintf(pBuf, nChars-1, szFormat, argList);
    
    // Ensure proper NULL termination.
    nActual = nUsed == -1 ? nChars-1 : Min(nUsed, nChars-1);
    pBuf[nActual + 1]= '\0';
   }
   while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES );
   
   // assign whatever we managed to format
   assign(pBuf, nActual);
  }

原创粉丝点击