“cin”和“File”的C通用接口

“cin”和“File”的C通用接口,第1张

概述cin和文件输入是否有通用接口? 我想制作一个具有可选参数的程序 prog [input-file] 如果指定了输入文件,那么它应该从文件中读取,如果没有,则应该从cin读取. 据我所知,他们都实现了istream.你将如何设置它以便我可以在>>中执行某些 *** 作var,其中in是一个istream. #include <iostream>#include <fstream>int main(i cin和文件输入是否有通用接口?

我想制作一个具有可选参数的程序

prog [input-file]

如果指定了输入文件,那么它应该从文件中读取,如果没有,则应该从cin读取.

据我所知,他们都实现了istream.你将如何设置它以便我可以在>>中执行某些 *** 作var,其中in是一个istream.

解决方法
#include <iostream>#include <fstream>int main(int argc,char **argv){    std::ifstream f;    if (argc >= 2) {        f.open(argv[1]);    }    std::istream &in = (argc >= 2) ? f : std::cin;    // use in here}

您可以将这项工作中的一部分转移到帮助程序类中,以使其更清晰(请注意,在无法打开文件的情况下,这种行为略有不同):

#include <iostream>#include <fstream>class ifstream_or_cin_t {    std::ifstream f;public:    ifstream_or_cin_t(const char *filename)    {        if (filename) {            f.open(filename);        }    }    operator std::istream &() { return f.is_open() ? f : std::cin; }};static voID do_input(std::istream &in){    // use in...}int main(int argc,char **argv){    do_input(        ifstream_or_cin_t((argc >= 2) ? argv[1] : NulL));}
总结

以上是内存溢出为你收集整理的“cin”和“File”的C通用接口全部内容,希望文章能够帮你解决“cin”和“File”的C通用接口所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1221880.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存