'iostream' Tips

An example program using ostringstream for formatting--
// iostream01.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <iomanipx.h>
using namespace std;


int main( int argc, char* argv[] )
{
   ostringstream os;
   os << "one";
   cout << os.str() << endl;
   os.str("");
   // or os.seekp(0); os.clear(0);
   os << "two";
   cout << os.str() << endl;
   
   os << "old stuff";
   cout << os.str() << endl;
   os.str("");
   os << "new stuff";
   cout << os.str() << endl;
   os.str("");

   os << padded_decimal<5>( 10 );
   cout << os.str() << endl;
   os.str("");

   os << odbc_date( 2001, 10, 9 );
   cout << os.str() << endl;
   os.str("");

   cout << currency( 100.3 ) << endl;
   cout << currency( 100.347 ) << endl;

   cout << currency( 100.342 ) << endl;
   return 0;
}
#include <sstream>
#include <iomanip>
using namespace std;

    ostringstream ach;
    ach << fixed << setprecision(2) << 2.345;

Mark Henri wrote:

> string s;
> ostringstream os;
> os << "{d'";
> os << dec << setfill('0') << setw( 4 ) << setiosflags(ios::right) << 2001;
> os << "-";
> os << dec << setfill('0') << setw( 2 ) << setiosflags(ios::right) << 4;
> os << "-";
> os << dec << setfill('0') << setw( 2 ) << setiosflags(ios::right) << 3;
> os << "'}";
> s = os.str();
> // was this way--
> // char ach[32];
> // sprintf( ach, "{d'%04d-%02d-%02d'}", m_year, m_month, m_day );
> // s = ach;

You are correct to try to fold that together. Code that expresses abilities 
Once and Only Once, at all scales, is well on the way to elegance & 
maintainability. If the code is folded together cleanly.

OTOH, you could fold it together like this:

template<int width> struct
decimal 
{
   int m_value;
   decimal(value): m_value (value) {}
   friend ostream & operator<< (ostream & out, decimal<width> &me)
   {
      out << dec << setfill('0') << setw( width ) 
      << setiosflags(ios::right) << m_value;
   }
};

Usage--
   os << decimal<4>(2001) << '-' << decimal<2>(4) << '-' << decimal<2>(3);
   // here's an example of erasing multiple items from
   // a list.
   list l;
   for ( int n=0; n < 10; n++ )
      l.push_back( n % 3 ); // 0 1 2 0 1 2 etc.

   for ( list::iterator i=l.begin(); i != l.end(); i++ )
      cout << *i << " ";
   cout << endl;

   i=l.begin();
   while (  i != l.end() )
   {
      if ( *i == 2 )
         i = l.erase( i );
      else
         i++;
   }

   for ( i=l.begin(); i != l.end(); i++ )
      cout << *i << " ";
   cout << endl;
W32QuickReference.html