在setiosflags函数中使用十六进制标志

Using hex flag inside setiosflags function

本文关键字:十六进制 标志 setiosflags 函数      更新时间:2023-10-16
int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;

上面的代码不起作用,但是如果我使用

cout<<hex

然后

cout<<setiosflags(ios::showbase|ios::uppercase)

然后它正在工作

为什么? 我怎么知道哪一个可以在setiosflags((中使用?

您需要先调用resetiosflags,然后再调用setiosflags。 这样做的原因是setiosflags(ios::hex|ios::showbase|ios::uppercase)只是将这些标志附加到流中,就像调用setf一样,这会在流中给出冲突的标志。 用

std::cout << std::resetiosflags(std::ios_base::dec)
<< std::setiosflags(std::ios::hex|std::ios::showbase|std::ios::uppercase)
<< a << endl;

将使其正确显示a

对于第一个版本,您首先必须清除std::ios::dec,否则它优先:

std::cout << resetiosflags (std::ios::dec);

您可以通过使用适当的掩码调用setf一次性执行此操作,例如:

std.cout.setf (std:ios.hex, std.ios.basefield);

正如cpp首选项中所述,std::cout << hex为您执行此操作。