提问人:Alex 提问时间:10/31/2022 最后编辑:user12002570Alex 更新时间:5/27/2023 访问量:128
为什么 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
问:
我正在学习C++的iostream。特别是,我了解到默认情况下,输出是右对齐的。例如,如果我写:cout
#include <iostream>
#include <iomanip>
int main()
{
std::cout << setw(10) << "abb" ; //this is guaranteed to print abb
}
然后保证输出:
abb
现在为了进一步澄清我的概念并确认我已经清楚地理解了这些东西,我编写了以下基本程序,其输出我无法理解。特别是,AFAIK 语句应该像这样打印,因为默认情况下输出是右对齐的。#1
#1
128
#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,因为默认情况下输出是右对齐的。#1
0
128
#1
所以我的问题是,即使默认情况下输出是右对齐的,为什么不打印语句。#1
128
答:
标志由 (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
评论
right