当我试图编译代码

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

GCC失败,抱怨operator=是私人的。是否有任何的方式来设置基于条件的istream为不同的值?

有帮助吗?

解决方案

您可以替换另一个CIN的流缓冲,并在某些程序,这是比身边掠过istreams没有提及直接CIN的总体战略简单。

int main(int argc, char* argv[]) {
  ifstream input;
  streambuf* orig_cin = 0;
  if (argc >= 2) {
    input.open(argv[1]);
    if (!input) return 1;
    orig_cin = cin.rdbuf(input.rdbuf());
    cin.tie(0); // tied to cout by default
  }

  try {
    // normal program using cin
  }
  catch (...) {
    if (orig_cin) cin.rdbuf(orig_cin);
    throw;
  }

  return 0;
}

尽管这是极为少见CIN控制离开主后使用,上面的try-catch避免不确定的行为,如果这件事情你的程序可能会做的。

其他提示

您可以使用用于in一个指针,例如:

istream *in;
ifstream ifn;

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

那么,是不是没有抱怨“没有合适的构造函数可用”?反正,可以修改它如以下

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);
    }
}

您可以在不影响这样流。你想达到什么可以用一个指向一个IStream虽然获得。

#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'
  // ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top