C++: assign cin to an ifstream variable?

前端 未结 2 760
再見小時候
再見小時候 2020-12-20 12:39

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

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


        
相关标签:
2条回答
  • 2020-12-20 12:48
    • Save the initial streambuf of cin into a variable
    • Change the streambuf of cin to the one from the file.
    • Do what you need to do
    • And don't forget to restore cin streambuf before closing your file -- RAII may help.
    0 讨论(0)
  • 2020-12-20 12:59

    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. :-)


    If you do want to be portable, and can make your program use istream, here's one way to do it:

    struct noop {
        void operator()(...) const {}
    };
    
    // ...
    
    shared_ptr<istream> input;
    if (filename == "-")
        input.reset(&cin, noop());
    else
        input.reset(new ifstream(filename.c_str()));
    

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

    0 讨论(0)
提交回复
热议问题