我正在嘗試將程式的輸出存盤在一個檔案中,盡管我知道有各種更簡單的方法,但我想使用字串來解決問題,因為我想知道它背后的邏輯。
到目前為止,我了解實作:
std:: stringstream s;
s << "string";
我知道在某個時候我會有以下代碼
cout << s.str()
但是如何在不提供字串本身的情況下將程式輸出存盤在字串流中?換句話說,如何將程式中的 cout 陳述句重定向到字串?
uj5u.com熱心網友回復:
如果您的目標是重定向std::cout到 a std::string,您可以使用該cout.rdbuf()方法提供std::cout不同的緩沖區來寫入,例如 a std::ostringstream(或 astd::ofstream等)的緩沖區。
上面的鏈接檔案提供了以下示例:
#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";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524461.html
