C++ “cin”的通用接口和“文件”
cin 和 file 输入有通用的接口吗?
我想制作一个具有可选参数的程序
prog [input-file]
如果指定了输入文件,那么它应该从该文件读取,如果没有,它应该从 cin 读取。
据我所知,它们都实现了 istream。你会如何设置它,以便我可以在 >> 中执行类似 的操作? var
,其中 in
是一个 istream
。
Is there a common interface for cin and file input?
I want to make a program that has an optional parameter
prog [input-file]
If an input file is specified, then it should read from the file, and if not, it should read from cin.
From what I can tell, they both implement istream
. How would you set up it so that I could do something like in >> var
, where in
is an istream
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将其中一些工作转移到帮助程序类中,以更清楚地了解发生了什么(请注意,在无法打开文件的情况下,其行为略有不同):
You could shift some of this work into a helper class to make it clearer what's going on (note that this has slightly different behavior in the case where the file can't be opened):
您可以编写一个引用
std::istream
的函数:用法示例:
You can write a function that takes a reference to an
std::istream
:Usage example:
我的2P价值:
My 2P worth:
或者
但是我认为这不是一个很好的方法,因为 cin 没有
close()
而 ifstream 有。or
However I think that this is not a very good method since cin doesn't have a
close()
whereas ifstream does.