【问题标题】:Trying to switch between std::cout and std::ifstream试图在 std::cout 和 std::ifstream 之间切换
【发布时间】:2013-06-25 06:22:54
【问题描述】:

我想从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
  }
}

对于大循环,很难同时维护这两个功能,因为循环部分是通用的,唯一的区别是输入源。

如何整合这两个功能?

【问题讨论】:

    标签: c++ ifstream cin


    【解决方案1】:

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

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

    然后切换到调用方。

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

    【讨论】:

    • 我认为你应该指出这是可行的,因为 std::cin 和 std::ifstream 都是 std::istream
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2011-09-02
      • 1970-01-01
      • 2010-10-12
      • 2013-10-18
      • 1970-01-01
      相关资源
      最近更新 更多