2015-12-03 45 views
0

由於我無法找到如何在android調試輸出中輸出原始數據(例如沒有\n自動插入),我決定繼承我們的日誌庫和緩衝區直到出現\n檢查std :: stringstream是否包含字符 - 緩存直到 n

我們的日誌庫接受的數據格式數量龐大,所以我決定創建一個模板方法:

template<typename T> 
bool addToLog(std::stringstream* stream, android_LogPriority priority, T data) { 
    // Add new data to sstream 
    stream<<data; 
    //If the stream now contains new line 
    if(stream->PSEUDO_containsCharacter('\n')) { 
     // remove everything before '\n' from stream and add it to string 
     std::string str = stream->PSEUDO_getAllStringBefore('\n'); 
     // Log the line 
     __android_log_print(priority, "", "%s", str.c_str()); 
     // Remove \n from stream 
     stream->PSEUDO_removeFirstCharacter(); 
    } 
} 

正如你所看到的,我不知道如何檢查\n是否是流並刪除它之前的一切。這是我需要的 - 緩衝區數據,直到\n,然後發送數據(沒有\n)到android日誌庫。

+0

'std :: getline'有什麼問題嗎? – LogicStuff

+0

@LogicStuff我認爲只適用於標準輸入,我從來沒有看到它被用於像這樣的目的。 –

+0

'std :: stringstream'和'std :: fstream'都是標準流 - [見層次結構](http://en.cppreference.com/w/cpp/io)。 – LogicStuff

回答

2

您可以檢查流中是否包含換行符,以便在字符串流的基礎字符串上使用std::string::find_first_of。如果流包含換行符,那麼我們可以使用std::getline在換行符之前提取緩衝區的部分並將其輸出到日誌。

template<typename T> 
bool addToLog(std::stringstream& stream, android_LogPriority priority, T data) { 
    // Add new data to sstream 
    stream << data; 
    //If the stream now contains new line 
    if(stream.str().find_first_of('\n', 0) != std::string::npos) { 
     // remove everything before '\n' from stream and add it to string 
     std::string str; 
     std::getline(stream, str); //gets output until newline and discards the newline 
     // Log the line 
     __android_log_print(priority, "", "%s", str.c_str()); 
    } 
} 
+0

注意'stream'是一個指針(錯誤?)。 – LogicStuff

+1

@LogicStuff感謝您的注意。這是OP所做的,我只是複製它。我將其改爲參考,因爲我沒有理由通過指針傳遞它。 – NathanOliver

+0

@NathanOliver我使用指針的原因是每個日誌級別都有單獨的流,而且這些流都是常量大小的數組。所以我只是傳遞數組指針(帶有偏移量) - 爲了進行參考(不是這個術語的混淆?),它不會真正提高性能。 –