簡體   English   中英

std :: cout,ostream和其他類型的獲取輸出流

[英]std::cout, ostream and other kinds of getting output stream

在我的項目(虛幻引擎4)中,我沒有輸出流,而是可以通過UE_LOG函數進行通信,該函數的工作原理與printf()非常相似。 問題是我只是制作了一個.dll庫(不包含Unreal包含),我想通過iostream進行通信。 我的想法是-在.dll庫中,我使用標准cout將消息寫入ostream,我在Unreal Engine函數中使用所有消息,在其中我以字符串形式獲取ostream並將其輸出到UE_LOG函數中。

問題是我一直把std::cout當作魔術的一部分,而不考慮里面到底是什么(我敢肯定我們大多數人都做過)。 我該如何處理? 簡單的方法不起作用(例如獲取stringstream並將其輸出到UE_LOG中)。

我的想法是-在.dll庫中,我使用標准cout將消息寫入ostream

實際上,您可以使用自己的實現替換std::cout使用的輸出緩沖區。 使用std::ostream::rdbuf()函數執行此操作(參考文檔中的示例):

#include <iostream>
#include <sstream>

int main()
{
    std::ostringstream local;
    auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer

    std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
        // buffer of 'local' object

    // now std::cout work with 'local' buffer
    // you don't see this message
    std::cout << "some message";

    // go back to old buffer
    std::cout.rdbuf(cout_buff);

    // you will see this message
    std::cout << "back to default buffer\n";

    // print 'local' content
    std::cout << "local content: " << local.str() << "\n";
}

(以防我的編輯未被正面評價)

來自OP:感謝您的提示,我終於找到了解決問題的方法。 假設我想從cout獲取流並將其發送到printf(因為我認為stdio庫優於iostream)。 在這里,我該怎么做:

#include <iostream>
#include <sstream>
#include <cstdio>

using namespace std;

class ssbuf : public stringbuf{
protected:
    int sync(){
        printf("My buffer: %s",this->str().c_str());
        str("");
        return this->stringbuf::sync();
    }
};


int main(){
    ssbuf *buf = new ssbuf();
    cout.rdbuf(buf);
    cout<<"This is out stream "<<"and you cant do anything about it"<<endl;
    cout<<"(don't) "<<"Vote Trump"<<endl;
}

代碼是很原始的,但是確實可以。 我使緩沖區的子類具有方法sync()向下轉換原始虛擬方法sync()。 除此之外,它的工作方式與通常的緩沖區一樣,只是抓住了所有控制台輸出流-正是我們想要的。 里面的str(“”)用來清理緩沖區-可能沒有輸出的流不會清理自身。

非常感謝您的幫助! 大GRIN為您服務! :d

暫無
暫無

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

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