Question

Adding new flags to control an ostream

Asked by: jdpipe

Hi all

I have a nice class for tracking units-of-measure along with numerical values.

I have a simple output method accompanying this class which I can use to make the units show whenever a value is outputted to an ostream, as shown below.

My question: instead of using the ios_base::showbase flag (which is really intended for something completely different), can I create a new flag that is guaranteed to work on all platforms, that won't clash with existing flags, and which can safely be set with the 'stream.flags()' method?

What would be the model approach here?

Any suggestions appreciated.

JP

---------------------8<------------------

#define DEFINE_OUTPUT_METHOD(MM,LL,TT,KK,II,UNITS) \
            inline \
            std::ostream& operator <<(std::ostream &os,const Units<MM,LL,TT,KK,II> &u){ \
                  double d = *reinterpret_cast<const double*>(&u); \
                  os << d; \
                  os.flags() & std::ios_base::showbase && os << " " << UNITS; \
                  return os; \
            }

DEFINE_OUTPUT_METHOD(0, 1, 0, 0, 0, "m");
DEFINE_OUTPUT_METHOD(0, 0, 1, 0, 0, "s");
DEFINE_OUTPUT_METHOD(0, 1, -1, 0, 0, "m/s");

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-11-21 at 23:25:42ID21215508
Topic

C++ Programming Language

Participating Experts
4
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ostream
    To C++ experts, If I want my print() function to be able to print things both on files and screen, is that better to declare the funtion as "void print(ostream &os)" or "void print(ostream os)" ? or any other format ? and why ? thanks. meow.
  2. OStream?
    I can't get my Printies function to print. #include <iostream> #include "letterset.h" int main() { ostream nikolai; letterSet samuel; samuel.printies(nikolai); return 0; } std::ostream & printies (std::ostream & outfile); std::ostream & let...
  3. ostream reference to ofstream(or ostream) object
    Hi, I have a global reference to an ofstream object(which i can change to ostream if reqd) ofstream fcout; In a fn.,i want to set the value of this global reference i.e. void func(ostream &fout) { fcout=fout;//this doesnt work.How to do this part? } I tried ostream ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jdpipePosted on 2004-11-21 at 23:27:41ID: 12641963

To clarify, this is how I use the above:

  Length L=5 * metre;
  cerr.flags(ios_base::showbase);
  cerr << "The car's length is "  << L << endl;

This would output:

  The car's length is 5 m

 

by: SteHPosted on 2004-11-22 at 02:39:47ID: 12642994

My approach would be to control the output of that class. Set a flag of that class and overwrite the <<operator () of that class to modify the oputput to your needs. Don't touch the well tested stream classes.

 

by: SteHPosted on 2004-11-22 at 02:41:51ID: 12643009

So your code should look like
Length L = 5, "metre";
L.flag (showunit);
cout << The car's length is " << L << endl;

 

by: rstaveleyPosted on 2004-11-22 at 03:53:39ID: 12643347

You may be looking for xalloc and iword (or if you want to make it more complicated pword).

Here's a way of handling display units with a standard length class.

--------8<--------
#include <iostream>
#include <iomanip>
#include <string>

// Globals for display units
namespace display {

      // Allocate our global ios_base::iword index for display units
      const int index = std::ios_base::xalloc();

      // Metres/Yards
      enum Units {Metres,Yards};

      // Get the ostream's display units
      template<typename C>
        inline Units get_units(std::basic_ostream<C>& os)
      {
            return static_cast<Units>(os.iword(index));
        }

      // Set the ostream's display unitys
        template<typename C>
      inline void set_units(std::basic_ostream<C>& os,Units value)
      {
            os.iword(index) = value;
      }

      // A manipulator to set the verbosity level
      class units {

            const Units value;

            template<typename C>
            friend std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os,const units &u)
            {
                  set_units(os,u.value);
                  return os;
            }

      public:
            units(Units value) : value(value) {}
      };

} // display namespace

// Class for storing length
class StandardLength {

      double length;            // Internally stored as metres
      template<typename C>
            friend std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os,const StandardLength& distance);

public:
      StandardLength() {}
      StandardLength(double standard_length) : length(standard_length) {}

      // Construct a StandardLength in yards
      static StandardLength Yards(double yards_length)
      {
            return StandardLength(yards_length/0.9144);
      }

      // Construct a StandardLength in metres
      static StandardLength Metres(double metres_length)
      {
            return StandardLength(metres_length);
      }

};

// Display the StandardLength
template<typename C>
std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os,const StandardLength& distance)
{
      return os << (display::get_units(os) == display::Yards ? distance.length*0.9144 : distance.length);
}

int main()
{
      StandardLength race_length = StandardLength::Metres(100);
      std::cout
            << "The race is "
            << display::units(display::Yards)
            << race_length
            << " yards, which is "
            << display::units(display::Metres)
            << race_length
            << " metres\n";
}
--------8<--------

BTW... Don't trust my metres/yards conversion - this was a quick hack :-)

 

by: jdpipePosted on 2004-11-22 at 06:35:04ID: 12644614

Thanks for the tips you guys...

STeH, this units class which I have needs to add zero overhead to storage and arithmetic operations, so I don't think that I can use a flag on top of the Units class, unless you had some clever way of doing it with static variables or something... But even then, I might want units being output in one stream, but not in another. For example, if I have a console window with some live results, showing units, but also afile with some tab-separated values. I would want both streams to keep their correct settings.

rstaveley, that stuff looks pretty good. I'm not familiar with xalloc and iword, I'll read up on those, check out your code, and get back to you.

Thanks again
JP

 

by: rstaveleyPosted on 2004-11-22 at 06:56:17ID: 12644807

> // A manipulator to set the verbosity level

That stray comment, which shouldn't be there, was left over from the facility for which I last used xalloc/iword. I had a flag which I put into the output stream to specify the verbosity of my debug.

I dug this stuff out of Standard C++ IOStreams and Locales by Langer and Kreft, which is worth flipping through, if you've got access to a library.

 

by: itsmeandnobodyelsePosted on 2004-11-22 at 11:34:00ID: 12647769

Actuall, i don't know why you are using 'showbase' flag:

I compiled using

#define DEFINE_OUTPUT_METHOD(MM,LL,TT,KK,II,UNITS) \
          inline \
          std::ostream& operator <<(std::ostream &os,const Units<MM,LL,TT,KK,II> &u){ \
               double d = *reinterpret_cast<const double*>(&u); \
               os << d; \
               /*os.flags() & std::ios_base::showbase && */os << " " << UNITS; \
               return os; \
          }

DEFINE_OUTPUT_METHOD(0, 1, 0, 0, 0, "m");
DEFINE_OUTPUT_METHOD(0, 0, 1, 0, 0, "s");
DEFINE_OUTPUT_METHOD(0, 1, -1, 0, 0, "m/s");

          Velocity v = 60. * kilometre / hour;
         
          Length x = 250. * kilometre;
         
          Time t = x / v;
          Length z = metre + metre;
          Units<0, 0, 0, 0, 0> unitless = 123.4;
          z = unitless * z;

          cerr << "The time taken to travel " << x << " at speed " << v << " is " << t << endl;
            // cerr.flags(ios_base::showbase);
            cerr << "The car's length is "  << z << endl;

not using any flag, and the output was fine:

The time taken to travel 250000 m at speed 16.6667 m/s is 15000 s
The car's length is 2 m

Regards, Alex

 

by: jdpipePosted on 2004-11-24 at 06:35:06ID: 12665697

The idea here is to be able to safely define a flag which can be used to turn on and off the display of units. I originally thought I would dodgily re-use the 'showbase' flag usually reserved (I think) for showing 0x (or whatever it is) at the start of binary values.

I think rstaveley's approach with 'iword' is going to be the right one.

JP

 

by: rstaveleyPosted on 2004-11-24 at 07:27:18ID: 12666300

I vote for rstaveley's approach too ;-)

 

by: itsmeandnobodyelsePosted on 2004-11-24 at 09:13:32ID: 12667623

I also, though that below looks simpler and runs on my VC6 system:

enum { showunit = ios_base::showbase };

#define DEFINE_OUTPUT_METHOD(MM,LL,TT,KK,II,UNITS) \
          inline \
          std::ostream& operator <<(std::ostream &os,const Units<MM,LL,TT,KK,II> &u){ \
               double d = *reinterpret_cast<const double*>(&u); \
               os << d; \
               os.flags() & showunit && os << " " << UNITS; \
               return os; \
          }

DEFINE_OUTPUT_METHOD(0, 1, 0, 0, 0, "m");
DEFINE_OUTPUT_METHOD(0, 0, 1, 0, 0, "s");
DEFINE_OUTPUT_METHOD(0, 1, -1, 0, 0, "m/s");


int main(int argc, char *argv[]){
   
     Velocity v = 60. * kilometre / hour;
     Length x = 250. * kilometre;
     Time t = x / v;
     Length z = metre + metre;
     Units<0, 0, 0, 0, 0> unitless = 123.4;
     z = unitless * z;
     cerr << "The time taken to travel " << x << " at speed " << v << " is " << t << endl;
 
     cerr.flags(showunit);
     cerr << "The car's length is "  << z << endl;
         
     return 0;
}

Regards, Alex

 

by: itsmeandnobodyelsePosted on 2004-11-24 at 10:21:04ID: 12668295

The reason why the above works is:

// extract from xiosbase header

        enum _Fmtflags {skipws = 0x0001, unitbuf = 0x0002,
                uppercase = 0x0004, showbase = 0x0008,
                showpoint = 0x0010, showpos = 0x0020,
                left = 0x0040, right = 0x0080, internal = 0x0100,
                dec = 0x0200, oct = 0x0400, hex = 0x0800,
                scientific = 0x1000, fixed = 0x2000, boolalpha = 0x4000,
                adjustfield = 0x01c0, basefield = 0x0e00,
                floatfield = 0x3000, _Fmtmask = 0x7fff, _Fmtzero = 0};
         ...
        _BITMASK(_Fmtflags, fmtflags);  // ==> typedef int fmtflags;
         ...
         fmtflags flags(fmtflags _Nf)
         {fmtflags _Of = _Fmtfl;
           _Fmtfl = _Nf & _Fmtmask;
           return (_Of); }


By switching on and off just before and after Units elements, you could avoid influences on other output elements:

      cerr << "The time taken to travel "
            << setiosflags(showunit) << x  << resetiosflags(showunit)
           << " at speed " << v << " is " << t << endl;

gives the following output:

The time taken to travel 250000 m at speed 16.6667 is 15000

Regards, Alex

 

by: guitaristxPosted on 2004-12-09 at 16:13:34ID: 12788894

Why not derive yourself a class from ostream, add the new flag in the derived class, and let everything else pass-through to the base class?

 

by: jdpipePosted on 2004-12-09 at 16:46:23ID: 12789035

Would that work, guitaristx?

I don't want to have to change the stream I'm outputting to; I want to be able to write

stringstream s;
s << displayunits << length << endl;

and

cerr << displayunits << speed << endl;

So I wouldn't have thought I'd want to overload the stream classes...

JP

 

by: SteHPosted on 2004-12-10 at 01:14:36ID: 12790703

I doubt that you want to derive a new stream class. Only the << operator needs to be overloaded in the tracking units class.

class track {
 [snip]

 bool bShowUnits; // this can be either static of normal member variable: a static would be good to switch unit output for all class objects.
                          // whereas a normal member allows to change output for each object indiviually.
public:
 friend ostream& operator<< (ostream&, track& tr1);
}

ostream& operator << (ostream& os, track& tr1)
{
  if (true == track::bShowUnits) // or (true == tr1.bShowUnits) for non static member var
     os << tr1.value << " " << tr1.unit;
  else
     os << tr1.value;

  return os;
}

 

by: guitaristxPosted on 2004-12-13 at 10:32:12ID: 12811789

If it was me implementing it, I would:

create a function:

void displayunits(void)
{
     if(app_globals::disp_units == true) app_globals::disp_units = false;
     else app_globals::disp_units == true;
}

And another so that you can use it:

ostream& operator <<(ostream& out, void (*func)(void) )
{
     func();
     return out;
}

Then, create output operators for all the types that you want to assign units to:

ostream& operator<<(ostream& out, const myType&obj)
{
     if(app_globals::disp_units)
     {
            //display with units
            out << obj.value << " " << obj.units;
     }
      else
      {
            //display without units
            out << obj.value;
      }

       return out;
}

There are some assumptions; one being that you've created an output operator for your "units" type.  This would be the easiest way, IMHO.  You might create disp_units as a public static member of your units class.

 

by: jdpipePosted on 2004-12-13 at 16:40:16ID: 12815210

Guitaristx

The units class I'm using here is one modified from http://www.embedded.com/shared/printableArticle.jhtml?articleID=9900094
you can see the code in current form at

http://cvs.sourceforge.net/viewcvs.py/freesteam/freesteam/units.h?rev=1.9&view=markup

The aim is to have zero runtime overhead on the units class. It's purely template related stuff which creates the output operator. Therefore there is no 'obj.units'.

Also, I want the display of units to be individually switched per stream. So I can have one stream open with units being written out, and another with no units being written.

JP

 

by: guitaristxPosted on 2004-12-14 at 09:59:55ID: 12821975

Wow....

Okay, after looking at your code, I'm going to recommend my original suggestion - overload the ostream class.  However, you may run into problems, since by overloading the class, you're making a subclass of ostream.  This being said, most people don't use ostream, they use subclasses of it (ofstream, ostringstream, etc).

What I'm thinking is something like this (and, unfortunately, you'll have to make overloads for all of the ostream-derived classes that you want to use, unless you want to get into multiple-inheritance):

class myofstream : public ofstream
{
protected:
     bool showunits;
public:
     void setShowUnits(bool set);
}

Now, make sure that you have overloaded output operators for your derived stream class(es).

Now, check out this URL:
http://www.informit.com/articles/article.asp?p=171014&seqNum=2
for instructions on how to implement a stream manipulator.  Manipulators are functions that operate on streams using the stream insertion operator (<<).  Now, you should be able to set this up so you can do this:

myofstream str("myfile.txt");
Units x = /*some value*/;
str << showunits(true) << x << endl;
str << showunits(false) << x << endl;

Is this the end result you're looking for?

 

by: jdpipePosted on 2004-12-14 at 20:07:27ID: 12826623

Yeah except I don't want to overload the stream classes, seems like a lot of clutter.

What about rstaverley's xalloc and iword suggestions?

JP

 

by: rstaveleyPosted on 2004-12-15 at 01:39:17ID: 12827857

Do you need any help with xalloc/iword, JP?

 

by: jdpipePosted on 2005-01-24 at 17:22:55ID: 13127749

Not abandoned, just a work in progress... I am interested in the answer but I haven't had a chance to test this xalloc/iword stuff

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...