操作后恢复 std::cout 的状态

新手上路,请多包涵

假设我有这样的代码:

 void printHex(std::ostream& x){
    x<<std::hex<<123;
}
..
int main(){
    std::cout<<100; // prints 100 base 10
    printHex(std::cout); //prints 123 in hex
    std::cout<<73; //problem! prints 73 in hex..
}

我的问题是,从函数返回后,是否有任何方法可以将 cout 的状态“恢复”到原来的状态? (有点像 std::boolalphastd::noboolalpha ..)?

谢谢。

原文由 UltraInstinct 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您需要 #include <iostream>#include <ios> 然后在需要时:

 std::ios_base::fmtflags f( cout.flags() );

//Your code here...

cout.flags( f );

您可以将它们放在函数的开头和结尾,或者查看有关如何将其与 RAII 一起使用的 答案

原文由 Stefan Kendall 发布,翻译遵循 CC BY-SA 4.0 许可协议

不是将格式注入 cout,而是采用 — << 方式,采用 setfunsetf 可能是更清洁的解决方案。

 void printHex(std::ostream& x){
  x.setf(std::ios::hex, std::ios::basefield);
  x << 123;
  x.unsetf(std::ios::basefield);
}

ios_base 命名空间也可以正常工作

void printHex(std::ostream& x){
  x.setf(std::ios_base::hex, std::ios_base::basefield);
  x << 123;
  x.unsetf(std::ios_base::basefield);
}

参考: http ://www.cplusplus.com/reference/ios/ios_base/setf/

原文由 aGuegu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题