流填充字符的默认定位
Default positioning of fill characters for streams
在std::setfill
的参考页上,有一个类似于下面程序的例子:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('*') << std::setw(10) << 42 << '\n';
}
它声称它应该打印:
********42
这表明填充字符的默认定位就像使用了 std::right
操纵器一样。
标准是否保证这是行为,还是我需要指定 std::right
才能确定?
此外,这是否仅适用于 std::cout
,还是适用于任何输出流?
setfill
在[std.manip]中定义为
template<class charT, class traits>
void f(basic_ios<charT, traits>& str, charT c) {
// set fill character
str.fill(c);
}
所以我们需要看看 ostream
的 fill
函数发生了什么,这在 [ostream.formatted.reqmts]/3 中有详细说明
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.
所以除非指定left
,否则填充字符在前。默认情况下,left
不是 cout
的设置标志,这在 Table 122: basic_ios::init() effects [tab:basic.ios.cons]
中有详细说明
在std::setfill
的参考页上,有一个类似于下面程序的例子:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('*') << std::setw(10) << 42 << '\n';
}
它声称它应该打印:
********42
这表明填充字符的默认定位就像使用了 std::right
操纵器一样。
标准是否保证这是行为,还是我需要指定 std::right
才能确定?
此外,这是否仅适用于 std::cout
,还是适用于任何输出流?
setfill
在[std.manip]中定义为
template<class charT, class traits>
void f(basic_ios<charT, traits>& str, charT c) {
// set fill character
str.fill(c);
}
所以我们需要看看 ostream
的 fill
函数发生了什么,这在 [ostream.formatted.reqmts]/3 中有详细说明
If a formatted output function of a stream os determines padding, it does so as follows. Given a
charT
character sequence seq wherecharT
is the character type of the stream, if the length of seq is less thanos.width()
, then enough copies ofos.fill()
are added to this sequence as necessary to pad to a width ofos.width()
characters. If(os.flags() & ios_base::adjustfield) == ios_base::left
istrue
, the fill characters are placed after the character sequence; otherwise, they are placed before the character sequence.
所以除非指定left
,否则填充字符在前。默认情况下,left
不是 cout
的设置标志,这在 Table 122: basic_ios::init() effects [tab:basic.ios.cons]