Search code examples
c++language-lawyeriomanip

Default positioning of fill characters for streams


On the reference page for std::setfill, there is an example similar to the following program:

#include <iostream>
#include <iomanip>
int main()
{
    std::cout << std::setfill('*') << std::setw(10) << 42 << '\n';
}

which claims that it should print:

********42

This suggests that the default positioning of the fill characters is as if the std::right manipulator was used.

Does the standard guarantee that this is the behavior, or do I need to specify std::right to be sure?

Also, does this work for just std::cout, or is it the same for any output stream?


Solution

  • setfill is defined in [std.manip] as

    template<class charT, class traits>
    void f(basic_ios<charT, traits>& str, charT c) {
      // set fill character
      str.fill(c);
    }
    

    so we need to look at what happens to an ostream's fill function and that is detailed in [ostream.formatted.reqmts]/3 as

    If a formatted output function of a stream os determines padding, it does so as follows. Given a charT character sequence seq where charT is the character type of the stream, if the length of seq is less than os.width(), then enough copies of os.fill() are added to this sequence as necessary to pad to a width of os.width() characters. If (os.flags() & ios_­base​::​adjustfield) == ios_­base​::​left is true, the fill characters are placed after the character sequence; otherwise, they are placed before the character sequence.

    So unless left is specified, the fill character come first. By default, left is not a set flag for cout and this is detail in Table 122: basic_­ios​::​init() effects   [tab:basic.ios.cons]