A Formatting String Function

Home
Back To Tips Page

How often have you been annoyed by not being able to be able to create a variable initialized to a formatted string, or have to declare a gratuitous variable just so you could use CString::Format with it?  Yes, probably a lot.  So I wrote the following little piece of code that allows me to create a formatted string result.

CString ToString(LPCTSTR fmt, ...);

It is easy to use.  For example

CString s = ToString(_T("value = %d"), value);

or

SomeFunction(ToString(_T("(%d, %d)"), x, y);

The code is so simple you can copy and paste it right from this page.  Therefore, there is no download.

It should be easy to generalize this to support FormatMessage for those of you who want that supported.

CString ToString(LPCTSTR fmt, ...);
CString ToString(UINT fmtid, ...);
#include "stdafx.h" 
#include "ToString.h" 
/**************************************************************************** 
*                         ToString 
* Inputs: 
*     LPCTSTR fmt: Format code 
*     ...: Values to format 
* Result: CString 
*     The values formatted to a string according to the format string 
****************************************************************************/ 

CString ToString(LPCTSTR fmt, ...) 
   { 
    va_list args; 
    va_start(args,fmt); 

    CString s; 
    s.FormatV(fmt, args); 

    va_end(args); 
    return s; 
   } // ToString 
   
/**************************************************************************** 
*                         ToString 
* Inputs: 
*     UINT fmt: String ID of formatting string 
*     ...: parameters to formatting string 
* Result: CString 
*     The result of the formatting 
****************************************************************************/ 

CString ToString(UINT fmtid, ...) 
   { 
    va_list args; 
    va_start(args,fmtid); 

    CString fmt; 
    fmt.LoadString(fmtid); 

    CString s; 
    s.FormatV(fmt, args); 

    va_end(args); 
    return s; 
   } // ToString 

[Dividing Line Image]

The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft.

Send mail to newcomer@flounder.com with questions or comments about this web site.
Copyright 1999-2007 FlounderCraft, Ltd.,  All Rights Reserved.
Last modified: May 14, 2011