试图在std :: cout和std :: ifstream之间切换

时间:2013-06-25 06:22:54

标签: c++ ifstream cin

我想读取std::cinstd::ifstream的输入,这些输入是从命令行确定的。该命令看起来像./run 1./run 2。现在,我必须根据读取模式编写两个几乎相似的函数。

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

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

对于大循环,很难保持这两个函数,因为循环部分是常见的,唯一的区别是输入源。

如何整合这两个功能?

2 个答案:

答案 0 :(得分:8)

std::cinstd::ifstream都是std::istream,因此您可以使用对std::istream的引用进行操作的函数来解决此问题。这适用于std::cinstd::ifstream个实例以及任何其他std::istream s:

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

然后打开来电方。

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

答案 1 :(得分:0)

std :: ifstream和std :: cin都是输入流,你可以用istream作为参数调用该函数