CString::Format

This method writes formatted data to a CString in the same way that sprintf formats data into a C-style character array. This method formats and stores a series of characters and values in the CString. Each optional parameter (if any) is converted and output according to the corresponding format specification in lpszFormat or from the string resource identified by nFormatID.

void AFX_CDECL Format(
LPCTSTR lpszFormat, ... ); 

void AFX_CDECL Format(
UINT nFormatID, ... ); 

Parameters

  • lpszFormat
    Specifies a format-control string.
  • nFormatID
    Specifies the string resource identifier that contains the format-control string.

Remarks

The call will fail if the string object itself is offered as a parameter to Format. For example, the following code:

CString str = "Some Data";
str.Format(_T("%s%d"), str, 123) );   // Attention: str is also used in the parameter list.

causes unpredictable results.

When you pass a character string as an optional argument, you must cast it explicitly as LPCTSTR. The format has the same form and function as the format argument for the _tprintf function. (For a description of the format and arguments, see in the Run-Time Library Reference.) A null character is appended to the end of the characters written.

Example

CString str;

str.Format(_T("Floating point: %.2f\n"), 12345.12345);
_tprintf(_T("%s"), (LPCTSTR) str);

str.Format(_T("Left-justified integer: %.6d\n"), 35);
_tprintf(_T("%s"), (LPCTSTR) str);

str.Format(IDS_SCORE, 5, 3);
_tprintf(_T("%s"), (LPCTSTR) str);

Output

If the application has a string resource with the identifier IDS_SCORE that contains the string "Penguins: %d\nFlyers : %d\n", the above code fragment produces this output:

Floating point: 12345.12
Left-justified integer: 000035
Penguins: 5
Flyers  : 3

Requirements

  Windows CE versions: 1.0 and later
  Header file: Declared in Afx.h
  Platform: H/PC Pro, Palm-size PC, Pocket PC

See Also

CString::GetBuffer