【问题标题】:Checking if input is standard input - istream检查输入是否为标准输入 - istream
【发布时间】:2013-12-14 07:03:45
【问题描述】:

给定以下简单的函数声明:

void foo (std::istream& is);

我可以通过多种方式调用 foo,例如:

fstream f;

foo(std::cin);
foo(f);

有什么方法可以检查给定的 istream& 是否是标准输入? (STD::CIN)

提前致谢

【问题讨论】:

  • 不可靠。这违背了使用istream 参数的目的。为什么不在你的函数中使用std::cin(如果你想要求标准输入)?
  • 好吧,operator== 适用于 std::istream...
  • 我想&is == &std::cin 应该很好用。

标签: c++


【解决方案1】:

您可以使用 if 语句进行检查

void foo (std::istream& is)
{
    if(is==std::cin)
    {
        std::cout<<"standard input"<< std::endl;
    }
    else
    {
        std::cout<<"file input"<< std::endl;
    }
}

【讨论】:

  • 请注意:它通过运算符 void* 比较底层流缓冲区的地址
猜你喜欢
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2021-09-29
  • 2018-05-26
  • 2018-02-21
  • 2012-02-03
相关资源
最近更新 更多