Click here to Skip to main content
15,614,270 members
Articles / Programming Languages / C
Article
Posted 1 Mar 2008

Stats

18K views
8 bookmarked

Simple manipulator for ostream for using printf style

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
1 Mar 2008CPOL
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.

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

The Code

C++
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)


Written By
Software Developer Arnisoft
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralBoost.Format Pin
Stephen Hewitt2-Mar-08 13:07
Stephen Hewitt2-Mar-08 13:07 

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.