C++与OSWATE和ISTRAM的简单流操作?

C++与OSWATE和ISTRAM的简单流操作?,c++,stream,iostream,cout,C++,Stream,Iostream,Cout,我一直在寻找解决方案,但找不到我需要/想要的 我所要做的就是将std::cout的流传递给一个函数,该函数对其进行操作。到目前为止,我使用的是一个模板函数: template<typename T> void printUpdate(T a){ std::cout << "blabla" << a << std::flush; } int main( int argc, char** argv ){ std::stringstream

我一直在寻找解决方案,但找不到我需要/想要的

我所要做的就是将std::cout的流传递给一个函数,该函数对其进行操作。到目前为止,我使用的是一个模板函数:

template<typename T>
void printUpdate(T a){
   std::cout << "blabla" << a << std::flush;
}

int main( int argc, char** argv ){

  std::stringstream str;
  str << " hello " << 1 + 4 << " goodbye";
  printUpdate<>( str.str() );

  return 0;
}
我更喜欢的是:

printUpdate << " hello " << 1 + 4 << " goodbye";

我试图做到:

void printUpdate(std::istream& a){
   std::cout << "blabla" << a << std::flush;
}
但这给了我:

error: invalid operands of types ‘void(std::istream&) {aka void(std::basic_istream<char>&)}’ and ‘const char [5]’ to binary ‘operator<<’

您不能将数据输出到输入流,这不是一件好事。 更改:

编辑2: 您需要将流传递给需要流的函数。 不能将字符串传递给需要流的函数。 试试这个:

  void printUpdate(std::ostream& out, const std::string& text)
  {
    std::cout << text << std::flush;
    out << text << std::flush;
  }

  int main(void)
  {
    std::ofstream my_file("test.txt");
    printUpdate(my_file, "Apples fall from trees.\n");
    return 0;
  }
链接输出流 如果要将内容链接到输出流,如函数的结果,则函数必须返回可打印的可流对象或相同的输出流

例如:

  std::ostream& Fred(std::ostream& out, const std::string text)
  {
    out << "--Fred-- " << text;
    return out;
  }

  int main(void)
  {
    std::cout << "Hello " << Fred("World!\n");
    return 0;
  }

不能将数据输出到输入流。将参数更改为std::ostream&a。另外,flush没有为输入流定义。我也尝试过。相同错误:错误:类型“voidstd::ostream&{aka voidstd::basic_ostream&}”和“const char[5]”的操作数对二进制运算符无效。在主函数中,需要为printUpdate函数调用提供流类型,例如printUpdate。不知道确切需要什么。但是,如果你想做任何看起来像printUpdate@Oguk的事情,谢谢,所以除了将printUpdate作为一个类之外,可能没有更简单的选择。我也尝试过。相同错误:错误:类型为'voidstd::ostream&{aka voidstd::basic_ostream&}'和'const char[5]'到binary'运算符的操作数无效错误消息与我的编辑中的示例不匹配,因为文本是std::字符串而不是5个字符的数组。抱歉,错误消息来自函数调用:printUpdate
void printUpdate(std::ostream& a){
   std::cout << "blabla" << a << std::flush;
}
void printUpdate(std::ostream& a)
{
  static const std::string text = "blabla";
  std::cout << text << std::flush;
  a << text << std::flush;
}  
  void printUpdate(std::ostream& out, const std::string& text)
  {
    std::cout << text << std::flush;
    out << text << std::flush;
  }

  int main(void)
  {
    std::ofstream my_file("test.txt");
    printUpdate(my_file, "Apples fall from trees.\n");
    return 0;
  }
  std::ostream& Fred(std::ostream& out, const std::string text)
  {
    out << "--Fred-- " << text;
    return out;
  }

  int main(void)
  {
    std::cout << "Hello " << Fred("World!\n");
    return 0;
  }