关于c++中的流

regarding streams in c++

本文关键字:c++ 关于      更新时间:2023-10-16

我想使用文件流和控制台输出流。在构造函数中,我希望根据传递给构造函数的参数使用文件或控制台输出流进行初始化。然后我将在类中有另一个函数,它将输出重定向到该流。它的代码是什么?我正在尝试下面的代码是不工作。欢迎提出其他设计建议。

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

应该这样做:

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

PSprintarray的变化。你所尝试的,与%s,是好的printf族的函数,但不是std::ostream

欢迎提出其他设计建议。

其中两个成员是无用的:

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

你不能用std::ios做任何事情,没有与streambuf关联的std::ostream是无用的,你永远不会使用filecout1 !

你想:

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

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

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

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