关于c ++中的流

时间:2014-05-28 20:56:08

标签: c++ ostream

我想使用文件流和consol输出流。在构造函数中,我想根据传递给构造函数的参数初始化文件或consol输出流。然后我将在类中有另一个函数,它将输出重定向到该流。它的代码是什么?我正在尝试下面的代码,这是无效的。 欢迎任何其他设计建议。

class Test
{
    private:

        std::ios *obj;
        std::ofstream file;
        std::ostream cout1;
    public:
//      Test(){}
        Test(char choice[])
        {
            if(choice=="file")
            {
                obj=new ofstream();
                obj->open("temp.txt");
            }
            else
                obj=new ostream();


        }
        void printarray()
        {
            for(int i=0;i<5;i++)

                     (*obj)<<"\n \n"<<"HI"
        }
}; 

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

#include <iostream>
#include <fstream>
#include <string>

class Test
{
   private:

      std::ofstream file;
      std::ostream& obj;

   public:

      // Use overloaded constructors. When the default constructor is used,
      // use std::cout. When the constructor with string is used, use the argument
      // as the file to write to.
      Test() : obj(std::cout) {}
      Test(std::string const& f) : file(f.c_str()), obj(file) {}

      void printarray()
      {
         for(int i=0;i<5;i++)
            obj<<"\n " << "HI" << " \n";
      }
}; 

int main()
{
   Test a;
   a.printarray();

   Test b("out.txt");
   b.printarray();
}

PS 查看printarray的更改。您使用%s尝试的内容适用于printf函数系列,但不适用于std::ostream

答案 1 :(得分:1)

  

欢迎任何其他设计建议。

其中两个成员没用:

    std::ios *obj;
    std::ofstream file;
    std::ostream cout1;

您无法对std::ios执行任何操作,与std::ostream无关联的streambuf无效,您永远不会使用file或者cout1无论如何!

你想:

    std::ofstream file;
    std::ostream& out;

如R Sahu的回答所示,并写信给out

    Test(char choice[])
    {
        if(choice=="file")

这不起作用,您需要使用strcmp来比较char个字符串。您应该使用std::string而不是char*