如何将控制台指定为要使用ostream写入的文件?

Aqu*_*irl 3 c++ file-io

coutostream类的一个对象.
另外,当我们写:

filebuf   objFileBuf;
objFileBuf.open ("test.txt", ios :: out);

ostream objOstream (&objFileBuf);
objOstream << "Test sentence\n";

objFileBuf.close();
Run Code Online (Sandbox Code Playgroud)

文本被写入文件.

如何将"console"指定为通过ostream写入的文件?

Naw*_*waz 8

你可以这样做:

ostream objOstream (cout.rdbuf());
objOstream << "Test sentence goes to console\n";
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

ostream & objOstream = cout;
objOstream << "Test sentence goes to console\n";
Run Code Online (Sandbox Code Playgroud)

第二个不适用于streambuf,而只是创建对the std::cout的引用,并使用引用.