Click here to Skip to main content
Licence CPOL
First Posted 9 Aug 2006
Views 38,161
Downloads 300
Bookmarked 12 times

How to Format a String

By | 9 Aug 2006 | Article
This article illustrates how to format a std::string using a variable argument list similar to CString's Format.

Introduction

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);
printf(buff);
_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
      va_end(marker); 
   }

   return retStr; 
}

Conclusion

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.

History

  • 9th August, 2006: Initial post

License

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

About the Author

Nitron

Engineer

United States United States

Member

Walter Storm is currently a research engineer for a large aircraft company. Originally from Tunkhannock, PA., he has a B.S. in Aerospace Engineering from Embry-Riddle Aeronautical University[^] with a minor in Psychology, and an M.S. in Systems Engineering from SMU[^]. He has been developing in C++ nearly full time since January of 2001. He is comfortable using MFC and has been known to hack at the STL with the best of them. He tends to be a perfectionist; especially when it comes to GUI design. When not integrating and testing flight control software or hacking at National Instruments'[^] software libraries, you can probably find him driving around in his 1990 2+2 Z32[^] (ok, another pic: Big Grin | :-D ) If by chance he's not in the Z, you may want to check for him here[^].
 
View Walter Storm's profile on LinkedIn.[^]

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberDeKaNszn15:09 16 Jan '12  
GeneralOverhead PinmemberMy2Cents12:54 27 Jun '09  
GeneralAverage Article [modified] PinmemberGeorge L. Jackson17:14 11 Aug '06  
GeneralRe: Average Article PinmemberNitron17:30 11 Aug '06  
GeneralRe: Average Article PinmemberNitron17:29 12 Aug '06  
GeneralGood article PinmemberRobert Edward Caldecott2:16 11 Aug '06  
GeneralRe: Good article PinmemberNitron2:59 11 Aug '06  
Question2.55?? PinmemberNitron14:55 10 Aug '06  
AnswerRe: 2.55?? Pinmemberjcoons16:18 13 Mar '07  

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.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 9 Aug 2006
Article Copyright 2006 by Nitron
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid