c++ - 操作后恢复 std::cout 的状态

标签 c++ iostream

假设我有这样的代码:

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..)?

谢谢。

最佳答案

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

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

//Your code here...

cout.flags( f );

您可以将它们放在函数的开头和结尾,或查看 this answer关于如何将其与 RAII 一起使用.

关于c++ - 操作后恢复 std::cout 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2273330/

相关文章:

c++ - 一行 Xerces 程序出错

带有 regexec() 的 C++ 正则表达式不匹配

c++ - 带有 Protocol Buffer 的 GzipOutputStream 和 GzipInputStream 的简单工作示例

C++ 检测输入重定向

java - 你能解释一下流的概念吗?

c++ - 使用通用 setter 设置数据成员

c++ - 测量算法的每字节周期

c# - 将 c++ dLL 的 char 指针数组传递给 c# 字符串

c++ - Cin 显示默认值

c++ - iostream 和大文件支持