vsprintf can not work on mac OS
-
On mac OS, the function vsprintf can't print string with parameter %s or %ls ,
but it works well on Windows.
I have tried on Qt5.8 and Qt5.9.Please help me, thanks.
code:#include <QCoreApplication>
#include <string>
using namespace std;wstring FormatStr( const wchar_t* wszFormat, ... )
{
va_list ptr;
va_start(ptr, wszFormat);int nLen = vwprintf(wszFormat, ptr) + 1; wchar_t* lpDest = new wchar_t[nLen]; vswprintf(lpDest, nLen, wszFormat, ptr); va_end(ptr); wstring strRe = lpDest; delete lpDest; return strRe;
}
string FormatStrA( const char* szFormat, ... )
{
va_list ptr;
va_start(ptr, szFormat);
int nLen = vprintf(szFormat, ptr) + 1;char* lpDest = new char[nLen]; vsprintf( lpDest, szFormat, ptr ); va_end(ptr); string strRe = lpDest; delete lpDest; return strRe;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
wstring str = FormatStr( L"%ls/%d/%d/%ls", L"https://www.google.com", 2, 3, L"asdfasdfasd");
string str1 = FormatStrA( "%s/%d/%d/%s", "https://www.google.com", 2, 3, "asdfasdfasd");// On windows: str == str1 == "https://www.google.com/2/3/asdfasdfasd" // On Mac: str == str1 == (null)/2/3/(null) return a.exec();
}
-
You use vprintf two times for the same valist ...
#include <string> #include <cwchar> #include <iostream> using namespace std; wstring FormatStr( const wchar_t* wszFormat, ... ) { va_list ptr; va_start(ptr, wszFormat); int nLen = vwprintf(wszFormat, ptr) + 1; va_end(ptr); std::cout<<" (1)"<<std::endl; wchar_t* lpDest = new wchar_t[nLen]; va_start(ptr, wszFormat); vswprintf(lpDest, nLen, wszFormat, ptr); va_end(ptr); wstring strRe = lpDest; delete lpDest; return strRe; } string FormatStrA( const char* szFormat, ... ) { va_list ptr; va_start(ptr, szFormat); int nLen = vprintf(szFormat, ptr) + 1; va_end(ptr); char* lpDest = new char[nLen]; std::cout<<" (2)"<<std::endl; va_start(ptr, szFormat); vsprintf( lpDest, szFormat, ptr ); va_end(ptr); string strRe = lpDest; delete lpDest; return strRe; } int main(int argc, char *argv[]) { wstring str = FormatStr( L"%ls/%d/%d/%ls", L"https://www.google.com", 2, 3, L"asdfasdfasd"); string str1 = FormatStrA( "%s/%d/%d/%s", "https://www.google.com", 2, 3, "asdfasdfasd"); std::wcout<<str<<" (3)"<<std::endl; std::cout<<str1<<" (4)"<<std::endl;
logs:
https://www.google.com/2/3/asdfasdfasd (1) https://www.google.com/2/3/asdfasdfasd (2) https://www.google.com/2/3/asdfasdfasd (3) https://www.google.com/2/3/asdfasdfasd (4)
on Mac OSX 10.9.5