为什么 cout.flags() & std::ios_base::right 打印 0,即使默认情况下输出是右对齐的

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

提问人:Alex 提问时间:10/31/2022 最后编辑:user12002570Alex 更新时间:5/27/2023 访问量:128

问:

我正在学习C++的iostream。特别是,我了解到默认情况下,输出是右对齐的。例如,如果我写:cout

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

然后保证输出:

abb


现在为了进一步澄清我的概念并确认我已经清楚地理解了这些东西,我编写了以下基本程序,其输出我无法理解。特别是,AFAIK 语句应该像这样打印,因为默认情况下输出是右对齐的。#1#1128#2

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  
    
}

演示。 程序的输出为:

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

正如我们在上面的输出中看到的,语句的输出是 而不是 。但我希望打印 128,因为默认情况下输出是右对齐的。#10128#1

所以我的问题是,即使默认情况下输出是右对齐的,为什么不打印语句。#1128

C++ 语言律师 IOSTREAM COUT 位标志

评论

1赞 463035818_is_not_an_ai 10/31/2022
cppref 说:“标准流的初始默认值等同于 right。我将其解释为最初没有设置任何标志,并且初始默认值与设置的效果相同,尽管我仍在寻找更可靠的来源right
0赞 apple apple 10/31/2022
不是回答,而是恕我直言,“我了解到默认情况下,cout 的输出是右对齐的”是不正确的,它是逐个字符输出到屏幕缓冲区,没有执行对齐。(只有指定宽度时才有效果格式,然后字符仍按顺序写入)

答:

1赞 apple apple 10/31/2022 #1

标志由 (from ostream 构造函数std::basic_ios::init)

它设置的唯一标志是 (§tab:basic.ios.consskipws | dec)


填充添加到左侧 (§ostream.formatted.reqmts, from $ostream.inserters.character)

给定一个 charT 字符序列 seq,其中 charT 是流的字符类型,如果 seq 的长度小于 os.width(),则根据需要将足够的 os.fill() 副本添加到此序列中,以填充到 os.width() 字符的宽度。如果 (os.flags() & ios_base::adjustfield) == ios_base::left 为 true,则填充字符放在字符序列之后;否则,它们将放在字符序列之前

所以没有标志的行为等于 。(垫前)ios_­base​::​right


注意:§Tab:Facet.num.put.fill for numbers