Printf and sprintf are common and vsprintf is not.
1. Declaration of the three functions:
int printf (const char * szFormat, ...);int sprintf (char * szBuffer, const char * szFormat, ...);int vsprintf(char *string, char *format, va_list param);
2. Example:
printf ("The sum of %i and %i is %i", 5, 3, 5+3) ;char szBuffer [100] ;sprintf (szBuffer, "The sum of %i and %i is %i", 5, 3, 5+3) ;puts (szBuffer) ;int sprintf (char * szBuffer, const char * szFormat, ...){ int iReturn ; va_list pArgs ; va_start (pArgs, szFormat) ; iReturn = vsprintf (szBuffer, szFormat, pArgs) ; va_end (pArgs) ; return iReturn ;}
3. Use of vsprintf
Under what circumstances does vsprintf work?
You can use vsprintf when the input parameters include... and you want to format and output the parameters in. For example, when a formatted string is displayed in the dialog box.
Sample Code:
void CTestDlg::ShowMessage(LPCTSTR lpFormat, ...){ LPTSTR lpStr = NULL; char buff[256]; if (lpFormat) { va_list argPtr; va_start(argPtr, lpFormat); vsprintf(buff, lpFormat, argPtr); lpStr = buff; } MessageBox(lpStr);}
Call code:
void CTestDlg::OnBnClickedButton(){ ShowMessage("%d : %s", 1, "Hello World!");}