C++ custom stream manipulator that changes next item on stream -


You print this number in hexadecimal in C ++:

  Int num = 10; Std :: cout & lt; & Lt; Std :: hex & lt; & Lt; Number; // = & gt; 'A'  

I know that I can make a manipulator which adds stuff to the stream like this:

  std :: ostream & Amp; Windows_feed (std :: ostream and out) {out & lt; & Lt; "\ R \ n"; Return; } Std :: cout & lt; & Lt; "Hello" & lt; & Lt; Windows_feed; // = & gt; "Hello \ r \ n"  

How, though, can I create a manipulator, such as 'hex', modifying objects to come in currents? As a simple example, how do I make a Ploson Manipater here?:

  int num2 = 1; Std :: cout & lt; & Lt; "1 + 1 =" & lt; & Lt; Plason & lt; & Lt; NUM2; // = & gt; "1 + 1 = 2" // Note that the values ​​stored in num2 do not change, only the display above it. Std :: cout & lt; & Lt; NUM2; // = & gt; First, you have to store some states in each stream. You can do this with that task and index, by which:  
  inline int geti () {static int i = ios_base :: xalloc (); Return i; } Ostream & amp; amp; Add_one (Ostream and OS) {os.iword (geti ()) = 1; Return os; } Ostream & amp; amp; Add_none (Ostream and OS) {os.iword (geti ()) = 0; Return os; }  

Being in place, you can already get some states in all the streams. Now, you just have to hook in the related output operation. Numerical output is done by one aspect, because this is probably dependent on the locale. Then you

  struct my_num_put: num_put & lt; Char & gt; can do. {Iter_type do_put (iter_type s, ios_base & amp; F; char_type fill, long v) const {return num_put & lt; Char & gt; :: do_put (s, f, fill, v + f.iword (geti ())); } Iter_type do_put (iter_type s, ios_base & amp; f, char_type fill, unsigned long v) const {return num_put & lt; Char & gt; :: do_put (s, f, fill, v + f.iword (geti ())); }};  

Now, you can test the stuff.

  int main (// output: 11121011 cout.imbue (locale, new my_num_put)); Cout & lt; & Lt; Add_one & lt; & Lt; 10 & lt; & Lt; 11 & lt; & Lt; Add_none & lt; & Lt; 10 & lt; & Lt; 1 1; }  

If you want only the next number to increase, simply set 0 to each code on do_put .


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -