cpp*_*cpp 9 c++ fstream ostream
如何确定天气ostream是文件或控制台流.在下面的程序中我想打印"Hello file!" 写入文件和"Hello console!"时 在写入控制台时.我应该在第17行指定什么条件?
#include <fstream>
#include<iostream>
#include <string>
using namespace std;
class A{
public:
A(string msg):_str(msg){}
string str()const {return _str;};
private:
string _str;
};
ostream & operator << (ostream & os, const A & a)
{
if (os is ofstream) //this is line 17
os << "Hello file! " << a.str() << endl;
else
os << "Hello console! " << a.str() << endl;
return os;
}
int main()
{
A a("message");
ofstream ofile("test.txt");
if (!ofile)
cerr << "Unable to open file";
else
ofile << a; // "Hello file"
cout << a << endl; // "Hello console"
}
Run Code Online (Sandbox Code Playgroud)
小智 4
也许不漂亮,但是
std::streambuf const * coutbuf = std::cout.rdbuf();
std::streambuf const * cerrbuf = std::cerr.rdbuf();
ostream & operator << (ostream & os, const A & a)
{
std::streambuf const * osbuf = os.rdbuf();
if ( osbuf == coutbuf || osbuf == cerrbuf )
os << "Hello console! " << a.str() << endl;
else
os << "Hello file! " << a.str() << endl;
return os;
}
Run Code Online (Sandbox Code Playgroud)
我们可以使用&os == &std::cout,但标准输出可能会重定向到文件,所以我认为最好使用 Streambuf 对象。(请参阅此答案以更好地了解重定向如何工作,以及为什么比较streambuf安全地解决了问题!)
| 归档时间: |
|
| 查看次数: |
1598 次 |
| 最近记录: |