随笔-6  评论-0  文章-0  trackbacks-0
很多时候想使用字符串格式化输出,但是std::wstring偏偏没有提供这个方法。CString只存在于ATL/MFC,使用Win32平台没有CString可用,使用底层的spintf之类的函数,又时常担心buffer越界,写重复的越界检测之类的代码...所以这里把CString的Format方法搬了过来:
String.h
1 class String : public std::wstring
2 {
3 public:
4     void Format(const wchar_t* pszFormat, );
5 protected:
6     void FormatV(const wchar_t* pszFormat, va_list args);
7     int GetFormattedLength(const wchar_t* pszFormat, va_list args);
8     int Format(wchar_t* pszBuffer, ULONG nLength, const wchar_t* pszFormat, va_list args);
9 };
String.cpp
std::wstring StrFormat( const wchar_t* pstrFormat,  )
{
    WCHAR szBuffer[300] = { 0 };
    va_list args;
    va_start(args, pstrFormat);
    ::wvnsprintf(szBuffer, lengthof(szBuffer) - 2, pstrFormat, args);
    wcscat_s(szBuffer, 300, L"\n");
    va_end(args);
    return szBuffer;
}

void String::Format( const wchar_t* pszFormat,  )
{
    va_list arglist;
    va_start(arglist, pszFormat);
    FormatV(pszFormat, arglist);
    va_end(arglist);
}

int String::Format( wchar_t* pszBuffer, ULONG nLength, const wchar_t* pszFormat, va_list args )
{
    return vswprintf_s(pszBuffer, nLength, pszFormat, args);
}

void String::FormatV( const wchar_t* pszFormat, va_list args )
{
    if (pszFormat == NULL)
    {
        return;
    }
    ULONG nLength = GetFormattedLength(pszFormat, args);
    wchar_t* pszBuffer = new wchar_t[nLength + 1];
    ::ZeroMemory(pszBuffer, nLength + 1);
    Format(pszBuffer, nLength + 1, pszFormat, args);
    std::wstring::operator=(std::wstring(pszBuffer));
    delete []pszBuffer;
}

int String::GetFormattedLength( const wchar_t* pszFormat, va_list args )
{
    return _vscwprintf(pszFormat, args);
}

以上代码在VS2008编译通过。

posted on 2015-07-29 18:23 weigtcs 阅读(1232) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理