use*_*576 14 c++ cout ofstream
在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块,但是如果可以的话我想避免使用它.有任何想法吗?
Ada*_*eld 36
使用参考.请注意,引用必须是类型std::ostream
,而不是std::ofstream
,因为std::cout
是std::ostream
,所以您必须使用最小公分母.
std::ofstream realOutFile;
if(outFileRequested)
realOutFile.open("foo.txt", std::ios::out);
std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);
Run Code Online (Sandbox Code Playgroud)
我假设您的程序行为类似于标准的unix工具,当没有给出文件时会写入标准输出,当给定文件时会写入该文件.您可以重定向cout
以写入另一个流缓冲区.只要您的重定向处于活动状态,写入cout的所有内容都会透明地写入您指定的目标位置.一旦重定向对象超出范围,就会放入原始流并输出再次写入屏幕:
struct CoutRedirect {
std::streambuf * old;
CoutRedirect():old(0) {
// empty
}
~CoutRedirect() {
if(old != 0) {
std::cout.rdbuf(old);
}
}
void redirect(std::streambuf * to) {
old = std::cout.rdbuf(to);
}
}
int main() {
std::filebuf file;
CoutRedirect pipe;
if(outFileRequested) {
file.open("foo.txt", std::ios_base::out);
pipe.redirect(&file);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,只要管道在main中存在,cout就会被重定向到该文件.您可以通过使其不可复制来使其更"生产就绪",因为它尚未准备好被复制:如果副本超出范围,它将恢复原始流.
归档时间: |
|
查看次数: |
12944 次 |
最近记录: |