64,648
社区成员
发帖
与我相关
我的任务
分享
int vprintf( std::wstring & strSrc, const wchar_t * pszArg, va_list argList )
{
int iAutoSize = 1024;
int iCopyCount = 0;
int iGrowthRate = 8;
std::wstring strTempBuff;
while ( true )
{
try
{
strTempBuff.resize( iAutoSize );
}
catch ( ... )
{
throw std::overflow_error( "String sprintf resize failed!" );
}
iCopyCount = vswprintf( ( wchar_t* )strTempBuff.data(), strTempBuff.length(), pszArg, argList );
if ( iCopyCount > 0 && iAutoSize > iCopyCount )
{
break;
}
//1k,8k,64k,512k,4m,32m,256m,-
iAutoSize *= iGrowthRate;
if ( iAutoSize < 0 )
{
throw std::overflow_error("String sprintf() failed, Autosize overflow!");
}
}
strTempBuff.resize( iCopyCount );
strSrc = strTempBuff;
return iCopyCount;
}
//格式化输出
int Format( std::wstring & strSrc, const wchar_t * pszArg, ... )
{
va_list argList;
va_start( argList, pszArg );
int iCopyCount = vprintf( strSrc, pszArg, argList );
va_end( argList );
return iCopyCount;
}
DECLARE_TEST_FUNC( TestUnicodeString_Format )
{
TEST_OUTPUT;
std::wstring a = L"zhang%s%sfei";
Format( a, a.c_str(), a.c_str(), a.c_str() );
std::wcout << L"Result:" << a << std::endl;
}
#include <stdio.h>
int main() {
wchar_t ws[100];
swprintf(ws,L"zhang%s%sfei", L"zhang%s%sfei", L"zhang%s%sfei" );
wprintf(L"%s\n",ws);
return 0;
}
//zhangzhang%s%sfeizhang%s%sfeifei
因为单步调试对应汇编时,我估计早晚要走到swprintf内部调用vswprintf处。此时你就可以参考人家swprintf是如何正确使用vswprintf了。Format( b, L"zhang%s%sfei", L"zhang%s%sfei", L"zhang%s%sfei" );
std::wstring a = L"zhang%s%sfei";
std::wstring b,c=a;
Format( b, c.c_str(), a.c_str(), a.c_str() );
std::wcout << L"Result:" << b << std::endl;
Format( b, (wchar_t *)a.c_str(), (wchar_t *)a.c_str(), (wchar_t *)a.c_str() );
std::wstring a = L"zhang%s%sfei";
std::wstring b;
Format( b, a.c_str(), a.c_str(), a.c_str() );
std::wcout << L"Result:" << b << std::endl;
std::wstring a = L"zhang%s%sfei";
std::wstring b;
Format( a, a.c_str(), a.c_str(), a.c_str() );
std::wcout << L"Result:" << b << std::endl;
std::wstring a = L"zhang%s%sfei";
std::wstring b;
Format( b, a.c_str(), a.c_str(), a.c_str() );
再试试看。