众所周知,在VS2010中,cout不受影响(请参见Stephan Lavavej here的帖子)。下面的代码如何使用cout的缓冲区构造ostream hexout?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    // Construct ostream hexout with cout's buffer and setup hexout to print hexadecimal numbers

    ostream hexout(cout.rdbuf());
    hexout.setf (ios::hex, ios::basefield);
    hexout.setf (ios::showbase);

    // Switch between decimal and hexadecimal output using the common buffer

    hexout << "hexout: " << 32 << " ";
    cout << "cout: " << 32 << " ";
    hexout << "hexout: " << -1 << " " ;
    cout << "cout: " << -1 << " ";
    hexout << endl;
}

最佳答案

每个流都有与之关联的basic_streambuf。 “未缓冲”仅表示basic_streambuf不维护内部缓冲区(一块内存)来缓冲输入/输出,而是直接从文件(或控制台等)读取/写入文件。

关于c++ - 下面的代码如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14532718/

10-09 22:46