Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How to reset the output stream manipulator flags [duplicate]

I've got a line of code that sets the fill value to a '-' character in my output, but need to reset the setfill flag to its default whitespace character. How do I do that?

cout << setw(14) << "  CHARGE/ROOM" << endl;
cout << setfill('-') << setw(11) << '-' << "  " << setw(15) << '-' << "   " << setw(11) << '-' << endl;

I thought this might work:

cout.unsetf(ios::manipulatorname) // Howerver I dont see a manipulator called setfill

Am I on the wrong track?

like image 702
noobzilla Avatar asked Sep 02 '25 05:09

noobzilla


2 Answers

You can use copyfmt to save cout's initial formatting. Once finished with formatted output you can use it again to restore the default settings (including fill character).

{
    // save default formatting
    ios init(NULL);
    init.copyfmt(cout);

    // change formatting...
    cout << setfill('-') << setw(11) << '-' << "  ";
    cout << setw(15) << '-' << "   ";
    cout << setw(11) << '-' << endl;

    // restore default formatting
    cout.copyfmt(init);
}
like image 61
deancutlet Avatar answered Sep 04 '25 21:09

deancutlet


Have a look at the Boost.IO_State_Savers, providing RAII-style scope guards for the flags of an iostream.

Example:

#include <boost/io/ios_state.hpp>

{
  boost::io::ios_all_saver guard(cout); // Saves current flags and format

  cout << setw(14) << "  CHARGE/ROOM" << endl;
  cout << setfill('-') << setw(11) << '-' << "  " << setw(15) << '-' << "   " << setw(11) << '-' << endl;
// dtor of guard here restores flags and formats
}

More specialized guards (for only fill, or width, or precision, etc... are also in the library. See the docs for details.

like image 35
Éric Malenfant Avatar answered Sep 04 '25 21:09

Éric Malenfant