Read from cin or a file

14,342

Solution 1

You could use a pointer for in, e.g.:

istream *in;
ifstream ifn;

if (argc==1) {
     in=&cin;
} else {
     ifn.open(argv[1]);
     in=&ifn;
}

Solution 2

So, is it not complaining "no appropriate constructor available" ? Anyways, you can modify it as below.

void Read(istream& is)
{
    string line;
    while (getline(is, line))
        cout << line;
}

int main(int argc, char* argv[])
{
    if (argc == 1)
        Read(cin);
    else
    {
        ifstream in("sample.txt");
        Read(in);
    }
}

Solution 3

You cannot affect streams like this. What you want to achieve can be obtained using a pointer to an istream though.

#include <fstream>
#include <istream>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
  istream *in;
  // Must be declared here for scope reasons
  ifstream ifn;

  // No argument, use cin
  if (argc == 1) in = &cin;
  // Argument given, open the file and use it
  else {
    ifn.open(argv[1]);
    in = &ifn;
  }
  return 0;

  // You can now use 'in'
  // ...
}
Share:
14,342
m42a
Author by

m42a

Updated on July 14, 2022

Comments

  • m42a
    m42a almost 2 years

    When I try to compile the code

    istream in;
    if (argc==1)
            in=cin;
    else
    {
            ifstream ifn(argv[1]);
            in=ifn;
    }
    

    gcc fails, complaining that operator= is private. Is there any way to set an istream to different values based on a condition?