tags:

views:

135

answers:

3

Hello Everyone,

Suppose I have a code like this:

void printHex(std::ostream& x){
    x<<std::hex<<123;
}
..
int main(){
    std::cout<<100; // prints 100 base 10
    printHex(std::cout); //prints 123 in hex
    std::cout<<73; //problem! prints 73 in hex..
}

My question is if there is any way to 'restore' the state of cout to its original one after returning from the function? (Somewhat like std::boolalpha and std::noboolalpha..) ?

Thanks, Iyer

+7  A: 

The Boost IO Stream State Saver seems exactly what you need. :-)

Example based on your code snippet:

void printHex(std::ostream& x) {
    boost::io::ios_flags_saver ifs(x);
    x << std::hex << 123;
}
Chris Jester-Young
+4  A: 

Googling gave me this:

  ios::fmtflags f;

  f = cout.flags(); // store flags

  cout.flags( f );

You'd probably want to put that at the head and end of your function.

Stefan Kendall
Yuck, whoever wrote that doesn't know C++ style, which is that one should aim to initialise variables straight away---`ios::fmtflags f(cout.flags())`---instead of the two-step "initialisation" as shown above.
Chris Jester-Young
I apologize for my crude copy and pasting from the internet. I admit, however, that I do not use c++ often. Feel free to edit if you think it makes it more semantic.
Stefan Kendall
Thanks! This is probably what I was looking for!
Srivatsan Iyer
@Stefan: I'm criticising whoever wrote it, not you. :-D
Chris Jester-Young
+3  A: 

With a little bit of modification to make the output more readable :

 void printHex(std::ostream& x){
     ios::fmtflags f(x.flags());
     x<<std::hex<<123<<"\n";
     x.flags(f);
  }


 int main(){
      std::cout<<100<<"\n"; // prints 100 base 10
      printHex(std::cout); //prints 123 in hex
      std::cout<<73<<"\n"; //problem! prints 73 in hex..
  }
nthrgeek
Using `(void)` for nullary functions is not usual C++ style; unlike C, in C++ `()` is always nullary. But yes, I acknowledge a strict reading of the C++ standard does require writing `int main(void)` and that `int main()` is non-conforming. Oh well. :-P
Chris Jester-Young
@Chris Jester-Young : Thanks :)
nthrgeek