You often need to format a string and populate it with relevant data before displaying a message box. For example
int nAge = 27;
TCHAR sName[]="Ajay";
float nSalary = 12500.50;
CString strMessage;<br>
strMessage.Format( _T("Name is %s, Age is %d, and salary is %.2f"),
sName, nAge, nSalary);<br>
AfxMessageBox(strMessage);</br></br>
What if this can be acheived by single statement:
AfxMessageBoxFormatted(_T("Name is %s, Age is %d, and salary is %.2f"),
sName, nAge, nSalary);
And here is implementation of
AfxMessageBoxFormatted
:
void AfxMessageBoxFormatted(LPCTSTR pFormatString, ...)
{
va_list vl;
va_start(vl, pFormatString);<br>
CString strFormat;
strFormat.FormatV(pFormatString, vl);
AfxMessageBox(strFormat);
}</br></br>
If you don't you MFC, or don't want to use, you can implement
MessageBoxFormatted
as:
void MessageBoxFormatted(HWND hWnd, LPCTSTR pCaption, LPCTSTR pFormatString, ...)
{
va_list vl;
va_start(vl, pFormatString);<br>
TCHAR strFormat[1024];
_vstprintf(strFormat, pFormatString, vl);<br>
::MessageBox(hWnd, strFormat, pCaption,MB_ICONINFORMATION);
}</br></br></br></br>
And use it as:
MessageBoxFormatted(NULL,
_T("Information"),
_T("Name is %s, Age is %d, and salary is %.2f"),
sName, nAge, nSalary);
If you don't understand stuff like
TCHAR
,
LPCTSTR
,
_T
, you better read this Tip/Trick:
What are TCHAR, WCHAR, LPSTR, LPWSTR, LPCTSTR etc?[
^]