c++language-lawyeriostreamcoutbitflags

Why cout.flags() & std::ios_base::right prints 0 even though by default the output is right aligned


I am learning C++'s iostream. In particular, I have learnt that by default the output of cout is right aligned. For example, if I write:

#include <iostream>
#include <iomanip>
int main()
{
    std::cout << setw(10) << "abb" ; //this is guaranteed to print        abb
}

then it is guaranteed to output:

abb


Now to further clear my concept and confirm that I have understood the things clearly, I wrote the following basic program whose output(of #1) I am not able to understand. In particular, AFAIK statement #1 should print 128 just like #2 because by default the output is right aligned.

int main()
{
    
    std::cout << "By default right: " << (std::cout.flags() & std::ios_base::right) << std::endl;     //#1 prints 0 NOT EXPECTED
    
    std::cout.setf(std::ios_base::right, std::ios_base::adjustfield);         //manually set right 

    std::cout << "After manual right: " << (std::cout.flags() & std::ios_base::right) << std::endl;     //#2 prints 128 as expected  
    
}

Demo. The output of the program is:

By default right: 0              <--------------WHY DOESN'T THIS PRINT 128 as by default output is right aligned??
After manual right: 128

As we can see in the above output, the output of statement #1 is 0 instead of 128. But I expected #1 to print 128 because by default the output is right aligned .

So my question is why doesn't statement #1 print 128 even though by default the output is right aligned.


Solution

  • the flags is set by std::basic_ios::init (from ostream constructor)

    and the only flag it set is skipws | dec (§tab:basic.ios.cons)


    and the padding is added to left (§ostream.formatted.reqmts, from $ostream.inserters.character)

    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 no flag behave equal to ios_­base​::​right. (pad before)


    note: §tab:facet.num.put.fill for numbers