Click here to Skip to main content
Click here to Skip to main content
Go to top

How to Format a String

, 9 Aug 2006
Rate this:
Please Sign up or sign in to vote.
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

Software Developer (Senior) Barbnet Investment Co.
United States United States
Walter Storm is currently a principal software engineer doing quantitative research for a private hedge fund. 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

Questionhow we can print class name , function name and line number in log file ? PingroupVijay Kumbhani22-May-13 19:19 
SuggestionPortable (ANSI) C++ code PinmemberMassood Khaari14-May-13 20:04 
GeneralMy vote of 1 PinmemberDeKaNszn16-Jan-12 15:09 
GeneralOverhead PinmemberMy2Cents27-Jun-09 12:54 
GeneralAverage Article [modified] PinmemberGeorge L. Jackson11-Aug-06 17:14 
GeneralRe: Average Article PinmemberNitron11-Aug-06 17:30 
GeneralRe: Average Article PinmemberNitron12-Aug-06 17:29 
GeneralGood article PinmemberRobert Edward Caldecott11-Aug-06 2:16 
GeneralRe: Good article PinmemberNitron11-Aug-06 2:59 
Question2.55?? PinmemberNitron10-Aug-06 14:55 
AnswerRe: 2.55?? Pinmemberjcoons13-Mar-07 16:18 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 9 Aug 2006
Article Copyright 2006 by Nitron
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid