发表一个格式化字符串的函数,类似于wsprintf的

来源:互联网 发布:你知我情深txt微盘 编辑:程序博客网 时间:2024/06/06 10:07

我们知道在格式化字符串的函数中如wsprintf,以及printf,还有MFC的CString类的Format函数中,会用到不定参数,但不定参数的使用比较麻烦,现在我做了一个格式化字符串的函数,虽然这个函数用到了不定参数,但不用我们分析不定参数,还是比较方便的,大家可以看看.

/*
函 数 名:FormatString
函数功能:用于ASCII码的格式化字符串,类似于wsprintf函数
返 回 值:返回szRet内字符的个数,返回-1表明失败
参 数  1:返回格式化后的字串,须指定长度为512
参 数  2:指定格式
说    明:在函数内说明了不定参数的用法
示    例:
 char sz[512] = {0};
 FormatString(sz, "hello = %d//n", 212);
*/
int FormatString(char *szRet, const char *lpszFormat, ...)
{
 if(szRet == NULL)
 {
  return -1;
 }
 va_list args;
 va_start(args, lpszFormat);

 int nBuf;
 char szBuffer[512];
 nBuf = _vsnprintf(szBuffer, 512, lpszFormat, args);
 strcpy(szRet, szBuffer);
 va_end(args);
 return nBuf;
}
/*
函 数 名:FormatString
函数功能:用于UNICODE码的格式化字符串,类似于wsprintf函数
返 回 值:返回wcsRet内字符的个数,返回-1表明失败
参 数  1:返回格式化后的字串,须指定长度为512
参 数  2:指定格式
说    明:在函数内说明了不定参数的用法
示    例:
 wchar_t wcs[512] = {0};
 int n = FormatString(wcs, L"hello hahah = %d, %x", 212, 100);
*/
int FormatString(wchar_t *wcsRet, const wchar_t *lpwcsFormat, ...)
{
 if(wcsRet == NULL)
 {
  return -1;
 }
 va_list args;
 va_start(args, lpwcsFormat);

 int nBuf;
 wchar_t wcsBuffer[512];
 nBuf = _vsnwprintf(wcsBuffer, 512, lpwcsFormat, args);
 wcscpy(wcsRet, wcsBuffer);
 va_end(args);
 return nBuf;
}

原创粉丝点击