Scene:
1. C language has its own sprintf function, but this function has a drawback, is that you do not know how much buffer to create, you can use the snprintf function to calculate the size, as long as the parameter buffer is null, count is 0.
2. This realization std::string own sprintf also uses the snprintf characteristic, calculates the size first, then creates the space, then deposits the std::string.
3. Variable parameter characteristics of C are also used.
Std::wstring Format (const wchar_t *format,...) {va_list Argptr;va_start (argptr, format); int count = _vsnwprintf (null,0,format,argptr); Va_end (argptr); Va_start ( ARGPTR, format); wchar_t* buf = (wchar_t*) malloc (count*sizeof (wchar_t)); _vsnwprintf (buf,count,format,argptr); va_end (argptr); std::wstring str (buf,count); free (buf); return str;}
Let's look at the declaration of a mutable parameter:
typedef char * va_list;
#define _INTSIZEOF (N) ((sizeof (n) + sizeof (int)-1) & ~ (sizeof (int)-1)) #define _crt_va_start (AP,V) (AP = (va_list) _addressof (v) + _intsizeof (v)) #define _CRT_VA_ARG (ap,t) (* (t *) (AP + = _intsizeof (t))-_intsizeof (t)) #d Efine _crt_va_end (AP) (AP = (va_list) 0)
NOTE: The AP will accumulate, each call to Va_arg will point to the next parameter, the problem is that va_arg do not know when to end, so if you design other variable parameters of the function, you must first pass in a parameter number as a method parameter.
SNPRINTF source code implementation is calculated by the number of% to determine the number of parameters.
Reference:
http://blog.csdn.net/echoisland/article/details/6086406
Https://msdn.microsoft.com/en-us/library/1kt27hek.aspx
Https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx
If buffer is a null pointer and count are zero, Len is returned as the count of characters required to format the output, n OT including the terminating null. To make a successful call with the same argument and locale parameters, allocate a buffer holding at least Len + 1 charact ERs.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[How to implement Std::string's own format (sprintf) function] []_[primary]_[]