std::ostream 忽略通过 setf() 在基础上设置的十六进制标志
std::ostream ignores hex flag set on the underlying via setf()
以下 C++ 代码意外地产生了十进制输出,显然忽略了对 setf()
的调用并打印了 true 42
。使用 std::setiosflags()
给出相同的结果。然而,使用 std::cout << std::hex
确实给出了预期的输出 true 0x2a
,因此 std::ios::showbase
和 std::ios::boolalpha
得到了尊重。
我已经在 Ubuntu 上测试了 G++ 5.4,在 CentOS 上测试了 G++ 7.2.1。我在这里错过了什么?
#include <sstream>
#include <iostream>
#include <iomanip>
#include <iterator>
int main()
{
std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
// Uncommenting the line below doesn't make a difference.
//std::cout << std::setiosflags(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
// Uncommenting this line does give the desired hex output.
//std::cout << std::hex;
int m = 42;
std::cout << true << ' ' << m << std::endl;
return 0;
}
以下 C++ 代码意外地产生了十进制输出,显然忽略了对 setf()
的调用并打印了 true 42
。使用 std::setiosflags()
给出相同的结果。然而,使用 std::cout << std::hex
确实给出了预期的输出 true 0x2a
,因此 std::ios::showbase
和 std::ios::boolalpha
得到了尊重。
我已经在 Ubuntu 上测试了 G++ 5.4,在 CentOS 上测试了 G++ 7.2.1。我在这里错过了什么?
#include <sstream>
#include <iostream>
#include <iomanip>
#include <iterator>
int main()
{
std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
// Uncommenting the line below doesn't make a difference.
//std::cout << std::setiosflags(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
// Uncommenting this line does give the desired hex output.
//std::cout << std::hex;
int m = 42;
std::cout << true << ' ' << m << std::endl;
return 0;
}