標籤:

Cout<<"hello"<<endl;具體做了什麼操作,endl不是起到換行和刷新緩衝區的作用嗎?為啥不加endl,也能立即顯示輸出內容?


下邊是ostream頭文件中的關於endl的一個聲明:

_CRTIMP2_PURE inline basic_ostream& &>

__CLRCALL_OR_CDECL endl(basic_ostream& &> _Ostr)

{ // insert newline and flush byte stream

_Ostr.put(
);//換行

_Ostr.flush();//刷新緩衝

return (_Ostr);

}

由此可見endl的確是起到換行和刷新的作用。至於為什麼不刷新也會顯示是因為緩衝區滿足一定條件後會自動刷新(緩衝區滿,長時間沒輸入等)。調用flush只不過是人為的強制它在此時執行。


符闖的回答,前半截是正確的,cout&<&<"hello";將這個字元串寫入輸出流對象cout

對endl的理解有一點點問題

由於cout會對輸出的內容進行緩衝,所以輸出的內容並不會立即輸出到目標設備(顯示器)

而是被存儲在緩衝區中,直到緩衝區填滿才輸出。

然而,我們可以在緩衝區沒有滿的時候,手動地刷新緩衝區以實現輸出

有兩種方式,一種是向cout輸出一個flush操作符,一種是向cout輸出一個endl操作符

flush只是刷新緩衝區

而endl不僅刷新緩衝區,還加入了一個換行符,endl = end line

例如:

cout&<&<"hello"&<&cout&<&<"world"&<&


The endl manipulator produces a newline character, exactly as the insertion of
does; but it also has an additional behavior: the streams buffer (if any) is flushed, which means that the output is requested to be physically written to the device, if it wasnt already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only when flushing the stream would be a feature and
when it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some devices it may produce a delay.

----來自http://www.cplusplus.com/doc/tutorial/basic_io/

有關於 endl 文章說的很清楚,有兩個作用:1.換行 2.刷新緩存區

一般 輸出的話,有兩種情況:1.刷新緩存區 2.緩存區滿的時候

但是一般情況下,不加endl大多數情況下,也能正常輸出,是因為在系統較為空閑時候,會查看緩存區的內容,如果發現新的內容,便進行輸出。但是 你並不清楚,系統什麼時候輸出,什麼時候不輸出,與系統自身的運行狀況有關。而刷新緩存區,是強制性的,絕對性的輸出。不取決於系統運行狀況

打一個很形象的比喻,

endl 相當於 一個 「要求」 -- 你不得不做 (現在,立刻做)

不加 endl 的情況,相當於 一個 「建議」 -- 你有空做下(你並不清楚,什麼時候做,做沒做)

talk is cheap, show you the code

代碼之下,了無秘密

可以親自測試一下如下代碼:

std::cout &<&< "the normal one! " &<&< std::endl; std::cout &<&< "the test! "; sleep(20); std::cout &<&< "the test is over" &<&< std::endl;

輸出結果:

the normal one!
the test! the test is over

而且 很明顯 在測試中發現 第一行the normal one輸出後,等待了較長時間 才輸出第二行,而且第二行的the test! the test is over 是同時輸出的。也就是說,你的第二行代碼 the test! 根本就沒有立刻輸出,只是在緩存器中,在sleep結束後,才進行輸出。

以下代碼 可做 對照組 作為參考

std::cout &<&< "the normal one! " &<&< std::endl; std::cout &<&< "the test! " &<&< std::endl; sleep(20); std::cout &<&< "the test is over" &<&< std::endl;


真正回答為什麼不加endl也能輸出

This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream.

來自http://cplusplus.com


緩衝區滿,輸出

程序結束,輸出

主動刷新,輸出

換行符,輸出


我覺得是將字元串「hello」寫進流對象cout對應的緩衝區,然後用endl來顯式刷新也即輸出,不解的是為啥不加endl,也能輸出


推薦閱讀:

C++異常處理寫的代碼太丑怎麼辦?
新手自學c++,推薦一些編譯器?
C 語言,「static 函數在內存中只有一份,普通函數在每次調用中維持一份拷貝」,這話怎麼理解?
C++ 派生類指針和基類指針可以在函數形參和實參上轉換嗎?
C語言、visual foxpro和ACCESS哪個更好學一些?

TAG:CC |