std::endl
來自 cppreference.com
定義於標頭檔案 <ostream> |
||
template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os ); |
||
將換行符插入到輸出序列 os 中,並重新整理它,就像呼叫 os.put(os.widen('\n')) 後接著呼叫 os.flush() 一樣。
這是一個僅用於輸出的 I/O 運算子,它可以與表示式 out << std::endl 一起呼叫,其中 out
是 std::basic_ostream 型別。
目錄 |
[edit] 注意
此運算子可用於立即生成一行輸出,例如,在顯示長時間執行程序的輸出、記錄多個執行緒的活動或記錄可能意外崩潰的程式的活動時。在呼叫 std::system 之前,如果派生程序執行任何螢幕 I/O,則也需要顯式重新整理 std::cout。在大多數其他常見的互動式 I/O 場景中,當與 std::cout 一起使用時,std::endl
是多餘的,因為來自 std::cin 的任何輸入、輸出到 std::cerr 或程式終止都會強制呼叫 std::cout.flush()。用 std::endl
代替 '\n'(某些來源鼓勵這樣做)可能會顯著降低輸出效能。
在許多實現中,標準輸出是行緩衝的,寫入 '\n' 無論如何都會導致重新整理,除非執行了 std::ios::sync_with_stdio(false)。在這些情況下,不必要的 endl
只會降低檔案輸出的效能,而不是標準輸出。
本 wiki 上的程式碼示例遵循 Bjarne Stroustrup 和 C++ 核心指南,僅在必要時重新整理標準輸出。
當需要重新整理不完整的輸出行時,可以使用 std::flush 運算子。
當需要重新整理每個輸出字元時,可以使用 std::unitbuf 運算子。
[edit] 引數
os | - | 輸出流的引用 |
[edit] 返回值
os(操作後的流的引用)。
[edit] 示例
用 '\n' 代替 endl
,輸出將是相同的,但可能不會即時顯示。
執行此程式碼
#include <chrono> #include <iostream> template<typename Diff> void log_progress(Diff d) { std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d) << " passed" << std::endl; } int main() { std::cout.sync_with_stdio(false); // on some platforms, stdout flushes on \n static volatile int sink{}; const auto t1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10000; ++j) for (int k = 0; k < 20000; ++k) sink += i * j * k; // do some work log_progress(std::chrono::high_resolution_clock::now() - t1); } }
可能的輸出
566ms passed 1133ms passed 1699ms passed 2262ms passed 2829ms passed
[edit] 另請參閱
控制每次操作後是否重新整理輸出 (函式) | |
重新整理輸出流 (函式模板) | |
與底層儲存裝置同步 ( std::basic_ostream<CharT,Traits> 的公共成員函式) |