9

Should be a trivial question, but found that setw only apply to its immediate following output, and not sure how to allow it apply to all the following output.

For example, for the following line of code

cout<<setw(3)<<setfill('0')<<8<<" "<<9<<endl;

or

cout.width(3);
cout.fill('0');
cout<<8<<" "<<9<<endl;

I want the output to be 008 009 instead of 008 9

Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117
  • possible duplicate of [Which iomanip manipulators are 'sticky'?](http://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky) – djf Jun 30 '13 at 21:03
  • Printing `" "` with width 3 would output 3 spaces, or even `"00 "` – anatolyg Jun 30 '13 at 21:07
  • Or duplicate of [Setting width in C++ output stream](http://stackoverflow.com/questions/7248627/setting-width-in-c-output-stream). – Simon Jun 30 '13 at 21:22

2 Answers2

7

setw isn't sticky, so you have to say it every time:

cout << setfill('0') << setw(3) << 8 << " "
     << setw(3) << 9 << endl;
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

Hmm. Use proxy struct for this.

struct setw_all_the_way {
    template <typename T> std::ostring &operator << (T &&t) {
        return std::cout << std::setw(14) << std::forward<T>(t);
    }
};
setw_all_the_way << ...;
Radosław Cybulski
  • 2,952
  • 10
  • 21