重定向后重置cout 我有一个C++程序,在程序中使用: static ofstream s_outF(file.c_str()); if (!s_outF) { cerr << "ERROR : could not open file " << file << endl; exit(EXIT_FAILURE); } cout.rdbuf(s_outF.rdbuf()); 流s_输出的静态(file.c_str()); 如果(!s_outp) { cerr
在更改重定向后重置cout 我有一个C++程序,在程序中使用: static ofstream s_outF(file.c_str()); if (!s_outF) { cerr << "ERROR : could not open file " << file << endl; exit(EXIT_FAILURE); } cout.rdbuf(s_outF.rdbuf()); 流s_输出的静态(file.c_str()); 如果(!s_outp) { cerr,c++,outputstream,C++,Outputstream,在更改cout的streambuf之前保存旧的streambuf: auto oldbuf = cout.rdbuf(); //save old streambuf cout.rdbuf(s_outF.rdbuf()); //modify streambuf cout << "Hello File"; //goes to the file! cout.rdbuf(oldbuf); //restore old streambuf cout &
cout
的streambuf之前保存旧的streambuf:
auto oldbuf = cout.rdbuf(); //save old streambuf
cout.rdbuf(s_outF.rdbuf()); //modify streambuf
cout << "Hello File"; //goes to the file!
cout.rdbuf(oldbuf); //restore old streambuf
cout << "Hello Stdout"; //goes to the stdout!
现在根据范围使用它,如下所示:
cout << "Hello Stdout"; //goes to the stdout!
if ( condition )
{
restorer modify(cout, s_out);
cout << "Hello File"; //goes to the file!
}
cout << "Hello Stdout"; //goes to the stdout!
cout
cout << "Hello Stdout"; //goes to the stdout!
if ( condition )
{
restorer modify(cout, s_out);
cout << "Hello File"; //goes to the file!
}
cout << "Hello Stdout"; //goes to the stdout!