将cout分配给变量名 [英] Assigning cout to a variable name

查看:340
本文介绍了将cout分配给变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ANSI C ++中,如何将cout流分配给变量名?我想做的是,如果用户指定了输出文件名,我在那里发送输出,否则,将其发送到屏幕。例如:

In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like:

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;

我试过这样做一个宏函数:

I tried doing this as a Macro function as well:

#define OUTPUT outFileRequested?outFile:cout

OUTPUT << "whatever" << endl;

但是这给我一个编译器错误。

But that gave me a compiler error as well.

我想我可以为每个输出使用一个IF-THEN块,但我想避免,如果我可以。有任何想法吗?

I supposed I could either use an IF-THEN block for every output, but I'd like to avoid that if I could. Any ideas?

推荐答案

使用参考。请注意,引用必须是 std :: ostream 类型,而不是 std :: ofstream ,因为 std :: cout std :: ostream ,因此必须使用最小公分母。

Use a reference. Note that the reference must be of type std::ostream, not std::ofstream, since std::cout is an std::ostream, so you must use the least common denominator.

std::ofstream realOutFile;

if(outFileRequested)
    realOutFile.open("foo.txt", std::ios::out);

std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);

这篇关于将cout分配给变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆