Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Visual C++ and MFC Fundamentals Chapter 10: Characteristics of a Window's Frame


9.6.5 String Formatting.................................................................................


The sprintf() function we reviewed earlier is provided by the C/C++ language. The
CString class provides its own function for formatting a string. This is done using the
CString::Format() whose syntax are:

void Format(LPCTSTR lpszFormat, ...);
void Format(UINT nFormatID, ...);

The lpFormat argument follows the exact same rules as the second argument to the
sprintf() function seen earlier. The nFormatID argument is an identifier that can have
been created using the String Table

The third and subsequent arguments follow the same rules as the ... argument of the
sprintf() function. There are many examples of the CString::Format() method in this
book.

While the sprintf() function and the CString::Format() methods follow the order of the
%Character combinations to format a message, the CString class provides a method that
can also be used to format a string but it allows you to list the parameters if the order of
your choice.

Here is an example:

void CExerciseDlg::OnMsgBox()
{
// TODO: Add your control notification handler code here
const char *DeptToContat = "Human Resources";
const char EmailContact[] = "[email protected]";
const int StartShift = 8;
const int EndShift = 6;
CString Msg;

Msg.Format("The name you entered is not in our records.\n"
"If you think there is a mistake, please contact %s "
"every week day from %d AM to %d PM.\n"
"You can also send an email to %s",
DeptToContat, StartShift, EndShift, EmailContact);

MessageBox(Msg, "Failed Logon Attempt");
}
Free download pdf