簡體   English   中英

關於C ++中的流

[英]regarding streams in c++

我想使用文件流和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"
        }
}; 

這樣的事情應該起作用:

#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沒有幫助。

任何其他設計建議均受到歡迎。

這些成員中有兩個是無用的:

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

使用std::ios和與streambuf無關的std::ostream不能執行任何操作,而且您也永遠不會使用filecout1

你要:

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

如圖中的R薩胡的回答,並寫out

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

這不起作用,您需要使用strcmp來比較char字符串。 您可能應該使用std::string而不是char*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM