Click here to Skip to main content
6,630,586 members and growing! (17,137 online)
Email Password   helpLost your password?
Languages » C / C++ Language » STL     Intermediate License: The Code Project Open License (CPOL)

Simple manipulator for ostream for using printf style

By Frank Arnold

A simple manipulator class for using printf style in ostream
C++ (VC6, VC7, VC7.1, VC8.0), C, STL, Dev
Posted:1 Mar 2008
Updated:1 Mar 2008
Views:5,093
Bookmarked:5 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
0 votes for this article

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


Member

Occupation: Software Developer
Company: Arnisoft
Location: Germany Germany

Other popular C / C++ Language articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralBoost.Format PinmvpStephen Hewitt14:07 2 Mar '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Mar 2008
Editor:
Copyright 2008 by Frank Arnold
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project