Click here to Skip to main content
15,168,235 members
Articles / Programming Languages / C++
Posted 9 Aug 2006


11 bookmarked

How to Format a String

Rate me:
Please Sign up or sign in to vote.
3.20/5 (21 votes)
9 Aug 2006CPOL1 min read
This article illustrates how to format a std::string using a variable argument list similar to CString's Format.


I've never been a big fan of variable argument lists for functions, if only for testing and verification's sake, and I'm still not quite sure where exactly I stand on the issue, but it's hard to argue that these functions don't come in handy when your only debugger is a hyperterm. 

I recently had a need to send formatted text to both a terminal window and a log file while performing some integration tasks. This was previously done by formatting a string (using sprintf) and sending that string (via printf) to a terminal and then logging the string to a file. OK, no big deal on the surface, but when you're doing this:

char buff[256] = {'\0'};
sprintf(buff, "test: %d %s\n", nTest, szTest);
_log << buff;

for the 30th time, it gets annoying. (Not to mention there is absolutely no guarantee against buffer overruns... nothing like introducing bugs into the system with your debugging code!)

The Solution

So I decided to come up with a solution to my ordeal, and here is the result (with some necessary changes courtesy of George's comments below):

std::string format(const char *fmt, ...) 
   using std::string;
   using std::vector;

   string retStr("");

   if (NULL != fmt)
      va_list marker = NULL; 

      // initialize variable arguments
      va_start(marker, fmt); 
      // Get formatted string length adding one for NULL
      size_t len = _vscprintf(fmt, marker) + 1;
      // Create a char vector to hold the formatted string.
      vector<char> buffer(len, '\0');
      int nWritten = _vsnprintf_s(&buffer[0], buffer.size(), len, fmt, marker);    

      if (nWritten > 0)
         retStr = &buffer[0];
      // Reset variable arguments

   return retStr; 


Well, that's really all there is to it.  Nothing very elaborate, but it does make for cleaner (and safer) code (compared to the first example anyway). Perhaps it can be of some value in your next project.


  • 9th August, 2006: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

CEO Aspen Insights
United States United States
Walter Storm is currently doing quantitative research and data science. Originally from Tunkhannock, PA., he has a B.S. in Aerospace Engineering from Embry-Riddle Aeronautical University[^], and an M.S. in Systems Engineering from SMU[^]. He has been professionally developing software in some form or another since January of 2001.

View Walter Storm's profile on LinkedIn.[^]

Comments and Discussions

BugBug in CRT Pin
Pandele Florin8-Jun-15 1:34
MemberPandele Florin8-Jun-15 1:34 
Questionhow we can print class name , function name and line number in log file ? Pin
Vijay Kumbhani22-May-13 20:19
MemberVijay Kumbhani22-May-13 20:19 
SuggestionPortable (ANSI) C++ code Pin
Khaari14-May-13 21:04
professionalKhaari14-May-13 21:04 
GeneralMy vote of 1 Pin
DeKaNszn16-Jan-12 16:09
MemberDeKaNszn16-Jan-12 16:09 
GeneralOverhead Pin
My2Cents27-Jun-09 13:54
MemberMy2Cents27-Jun-09 13:54 
GeneralAverage Article [modified] Pin
George L. Jackson11-Aug-06 18:14
MemberGeorge L. Jackson11-Aug-06 18:14 
GeneralRe: Average Article Pin
Nitron11-Aug-06 18:30
MemberNitron11-Aug-06 18:30 
GeneralRe: Average Article Pin
Nitron12-Aug-06 18:29
MemberNitron12-Aug-06 18:29 
GeneralGood article Pin
Rob Caldecott11-Aug-06 3:16
MemberRob Caldecott11-Aug-06 3:16 
GeneralRe: Good article Pin
Nitron11-Aug-06 3:59
MemberNitron11-Aug-06 3:59 
Question2.55?? Pin
Nitron10-Aug-06 15:55
MemberNitron10-Aug-06 15:55 
AnswerRe: 2.55?? Pin
jcoons13-Mar-07 17:18
Memberjcoons13-Mar-07 17:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.