mahmood
mahmood

Reputation: 24715

Trying to switch between std::cout and std::ifstream

I want to read inputs from either std::cin or std::ifstream which are determined from the command line. The command looks like ./run 1 or ./run 2. Right now, I have to write two almost similar functions based on the read mode.

void read1()
{
  int a, b;
  while (std::cin >> a >> b) {
    // do something
  }
}

or

void read2()
{
  int a, b;
  std::ifstream fin("file.txt");
  while (fin >> a >> b) {
    // do something
  }
}

For big loops it is difficult to maintain both functions since the loop part is common and the only difference is input source.

How can I integrate the two functions?

Upvotes: 2

Views: 371

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

std::cin and std::ifstream are both std::istreams, so you could solve this problem by using a function that operates on a reference to std::istream. This would work in std::cin, std::ifstream instances, and any other std::istreams:

void read(std::istream& input)
{
  while (input >> a >> b) { .... }
}

then switch on the caller side.

if (something)
{
  read(std::cin);
} else
{
  isfream input(....);
  read(input);
}

Upvotes: 7

Enigma
Enigma

Reputation: 1717

both std::ifstream and std::cin are inputstreams, you can call the function with a istream as argument

Upvotes: 0

Related Questions