Common C ++ interface for "cin" and "File"

Is there a common interface for cin and file input?

I want to create a program with an optional parameter

prog [input-file]

If an input file is specified, it must be read from the file, and if not, it must be read from cin.

From what I can say, they both implement istream. How would you set it up so that I can do something like in >> varwhere it inis istream.

+3
source share
4 answers
#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
}

You can transfer part of this work to a helper class to clarify what happens (note that this has slightly different behavior when the file cannot be opened):

#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));
}
+7

, std::istream:

void do_input(std::istream& the_istream)
{
    int my_awesome_variable;
    the_istream >> my_awesome_variable;
}

:

int main()
{
    // reading from stdin:
    do_input(std::cin);

    // reading from a file:
    std::ifstream fs("test.txt");
    do_input(fs);
}
+7

My 2P is worth:

#include <iostream>
#include <fstream>
#include <string>

extern char const* findFlag(int,char*[],char const*);
int main(int argc,char* argv[])
{
    std::string     isFile  = findFlag(argc,argv,"-f");
    std::ifstream   file;

    if (isFile != "")
    {   file.open(isFile.c_str());
    }
    std::istream&   data    = isFile != "" ? file : std::cin;


}
+1
source
istream& input = cin;

or

inputFileStream ifstream(fileName);
istream& input = inputFileStream;

However, I believe that this is not a very good method, since cin does not close(), whereas ifstream does.

-1
source

Source: https://habr.com/ru/post/1766497/


All Articles