2013-09-28 90 views
0

我已經在Linux(Ubuntu 12.04)平臺的C++中編寫了一個程序,該程序在每秒鐘將標準輸出打印到標準輸出中。這意味着,在10秒鐘後,標準輸出中有100行(每秒標準輸出爲2行報告)。將stdout寫入字符串變量

這是我應用的模擬格式,我不能更改任何變量或方法來將輸出寫入變量而不是標準輸出。

我打算將此輸出保存到字符串變量中而不是標準輸出。 C++語言怎麼可能?

+0

當你說「stdout」時,你的意思是你使用'printf()'還是'fprintf(stdout,...)'?在那種情況下,我不認爲有解決方案。如果你的意思是'std :: cout',那麼有一個解決方案。 –

回答

1

您可以爲此使用字符串流。假設你原來的日誌記錄功能是這樣的:

void log(std::ostream & o, std::string msg) 
{ 
    o << msg << std::endl; 
} 

int main() 
{ 
    // ... 
    log(std::cout, "Ping"); 
} 

更改爲:

#include <sstream> 

int main() 
{ 
    std::ostringstream oss; 

    // ... 
    log(oss, "Ping"); 
} 

如果這不是一個選項,你可以裂傷全球std::cout的輸出緩衝:

std::streambuf * sbuf = std::cout.rdbuf(); // save original 

std::ostringstream oss; 
std::cout.rdbuf(oss.rdbuf());    // redirect to "oss" 

// ... 

std::cout.rdbuf(sbuf);      // restore original 

無論如何,oss.str()都包含字符串數據。

+0

如何使用默認程序打印stdout打印並允許使用我的格式在stdout中打印自己的字符串變量(oss.str())? – BlueBit

+0

@BlueBit:對不起,我不明白你的問題。你想格式化什麼? –

+0

我的意思是,我不想在我的程序中打印我的默認標準輸出。只需將stdout複製到字符串變量中即可。我怎樣才能打印標準輸出?明確嗎,朋友? :-) – BlueBit