Click here to Skip to main content
Licence CPOL
First Posted 1 Mar 2008
Views 8,635
Bookmarked 7 times

Simple manipulator for ostream for using printf style

By | 1 Mar 2008 | Article
A simple manipulator class for using printf style in ostream

Introduction

Some people often wishes a "printf" style for using with the IO-Streams like the (w)stringstream class.

With some lines of code and the knowledge of manipulators, this is not a big deal. In this example I use the Unicode variant of the stringstream class. But with some changes it works also with the multibyte variants.

Using the code

Put the manipulator in your stream ;) Here I use the Unicode variant of the stringstream class.

            wstringstream stream;
            stream << L"All about this " << PrintF(L"%d", 20) << endl;           
          

The Code

class PrintF
{
public:
 ~PrintF(){ delete[] buf;}
    explicit PrintF(const WCHAR* fmt,...){
        va_list args;
        va_start(args, fmt);
        size_t len = _vscwprintf(fmt, args ) + 1;
        buf = new WCHAR[len+1];
        vswprintf_s( buf, len, fmt, args); 
    }
    friend wostream&  operator <<(wostream &os, const PrintF &pf);
private:
    WCHAR* buf;
};

//manipulator
inline wostream& 
operator <<(wostream &os, const PrintF &pf){ os << pf.buf; return os; }

 

License

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

About the Author

Frank Arnold

Software Developer
Arnisoft
Germany Germany

Member



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
GeneralBoost.Format PinmvpStephen Hewitt13:07 2 Mar '08  
Another option is to use Boost's Format[^] library.
 
Steve

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
Web04 | 2.5.120529.1 | Last Updated 1 Mar 2008
Article Copyright 2008 by Frank Arnold
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid