Formatting (sprintf-style) |
![]() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Format is similar to the C sprintf() function; it will take a format string (either as the fmt parameter, or from the string resource table in FormatRes) and a variable number of arguments and will build a result string, storing it in the Str object.
Format destroys any previous content of the object. However, if the caller has preallocated a buffer, the buffer will be preserved and the methods will be slightly faster (they will not need to estimate buffer size).
AppendFormat does not destroy the previous content, but appends the formatted data to it instead.
All three methods return a reference to self (i.e. the object on which the method is called) for convenience.
The set of format specifiers is a subset of what's available for sprintf():
| %s |
A const STRCHAR* string. The type of string must match the Str Library Unicode/ANSI build, i.e. pass const STRACHAR* in ANSI builds, const STRWCHAR* in Unicode builds. The format specifier may include a .precision clause limiting the number of characters to be printed. |
| %S |
Like %s, but accepts a Unicode string if the library is compiled in ANSI mode, and vice versa |
| %! | A direct pointer to a Str object. Acts like %s but you can directly pass the address of a Str object. No precision clause is allowed. |
| %e, %E, %f, %g, %G |
A double value. See sprintf() reference for an explanation of each, plus the allowed format precision specifiers. |
| %c, %C, %d, %i, %o, %u, %x, %X |
An integer value. See sprintf() reference for an explanation of each, plus the allowed format precision specifiers. |
| %p | A 32-bit linear pointer value. Useful for debugging utilities, etc. |
| %n | Not supported with Str. Normally, would store the # of characters printed so far |
| %S | Not currently supported with Str. Normally, would act like %s but accept Unicode in ANSI apps, and vice versa |
Example 1: Form a person's name and age
Str s_name (_T("John"));
const STRCHAR* s_fam = _T("Doe");
int age = 30;
Str result;
result.Format (_T("%! %s %d"), &s_name, s_fam, age);
ASSERT (result == _T("John Doe 30"));
Example 2: Use advanced formatting with %f
Str result;
result.Format ("%.3f", 16.2); // 3 digits after dot
ASSERT (result == _T("16.200"));
result.Format ("%.*f", 4, 16.2); // variable number - 4 in this case - digits after dot
ASSERT (result == _T("16.2000"));
result.Format ("%0*.*f", 3, 0, 16.7); // variable digits - 3 zero-prefixed before, 0 after dot
ASSERT (result == _T("017"));
|
|
|
|
|
Equivalent to Format(), but accepts a C-standard va_list type argument. This facilitates user-defined methods and functions that accept variable-length argument lists, do some processing on them, and store intermediate results in a Str object.
See also: Adding to Strings