C ++:将cin分配给ifstream变量? [英] C++: assign cin to an ifstream variable?

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

问题描述

您知道常见的stdio成语, stdin 是由
a指定的文件名 - ,例如

You know the common stdio idiom that stdin is specified by a filename of "-", e.g.

if ((strcmp(fname, "-"))
    fp = fopen(fname);
else
    fp = stdin;

使用 ifstream 实例?我收到
a位的代码,有一个 ifstream 作为类的一部分,我会
喜欢添加代码做等效,类似:

What's the best way to do this with an ifstream instance? I've received a bit of code that has an ifstream as part of a class and I'd like to add code to do the equivalent, something like:

if ( filename == "-")
    logstream = cin;  // **how do I do this*?*
else
    logstream.open( filename.c_str() );


推荐答案

cin 不是 ifstream 如果你可以使用 istream ,那么你就是赢了,否则,如果你准备是不可移植的,只需打开 / dev / stdin / dev / fd / 0 或任何。: - )

cin is not an ifstream, but if you can use istream instead, then you're in to win. Otherwise, if you're prepared to be non-portable, just open /dev/stdin or /dev/fd/0 or whatever. :-)

如果您希望可移植,并且可以让您的程序使用 istream ,方法做:

struct noop {
    void operator()(...) const {}
};

// ...

shared_ptr<istream> input;
if (filename == "-")
    input.reset(&cin, noop());
else
    input.reset(new ifstream(filename.c_str()));

noop cin 情况下不执行任何操作,因为 cin 不意味着被删除。

The noop is to specify a deleter that does nothing in the cin case, because, well, cin is not meant to be deleted.

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

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