在ANSI C++中,如何将cout流分配给变量名?我想要做的是,如果用户指定了输出文件名,我在那里发送输出,否则,将其发送到屏幕.所以类似于:
ofstream outFile;
if (outFileRequested)
outFile.open("foo.txt", ios::out);
else
outFile = cout; // Will not compile because outFile does not have an
// assignment operator
outFile << "whatever" << endl;
Run Code Online (Sandbox Code Playgroud)
我也尝试将其作为宏函数:
#define OUTPUT outFileRequested?outFile:cout
OUTPUT << "whatever" << endl;
Run Code Online (Sandbox Code Playgroud)
但这也给了我一个编译器错误.
我想我可以为每个输出使用IF-THEN块,但是如果可以的话我想避免使用它.有任何想法吗?