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

夙愿已清 提交于 2019-11-30 17:19:05
Éric Malenfant

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.

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);
}

You can use the ios::fill() function to set and restore the fill character instead.

http://www.cplusplus.com/reference/iostream/ios/fill/

#include <iostream>
using namespace std;

int main () {
  char prev;

  cout.width (10);
  cout << 40 << endl;

  prev = cout.fill ('x');
  cout.width (10);
  cout << 40 << endl;

  cout.fill(prev);

  return 0;
}
Dmitry V

You can manually change the setfill flag to whatever you need it to be:

float number = 4.5;
cout << setfill('-');
cout << setw(11) << number << endl; // --------4.5
cout << setfill(' ');
cout << setw(11) << number << endl; // 4.5

The null character will reset it back to the original state: setfill('\0')

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!