1. 程式人生 > >C++ 大多數人將 cin::sync() 視為清除緩存區函數的誤用

C++ 大多數人將 cin::sync() 視為清除緩存區函數的誤用

associate fill ted oci tro som for pre 緩沖區

一百度,大多數人將cin::sync()函數直接理解為清空緩沖區的函數,然而如果在VS2017編譯器上,就會發現並不能清空緩沖區,為什麽呢?

http://en.cppreference.com/w/cpp/io/basic_istream/sync

根據此標準文檔中的說明:

該函數的作用為:Synchronizes the input buffer with the associated data source.

然後重點:

As with readsome(), it is implementation-defined whether this function does anything with library-supplied streams. The intent is typically for the next read operation to pick up any changes that may have been made to the associated input sequence after the stream buffer last filled its get area. To achieve that, sync()

may empty the get area, or it may refill it, or it may do nothing. A notable exception is Visual Studio, where this operation discards the unprocessed input when called with a standard input stream.

此函數是: implementation-defined


所以實現上,可不一定能清空緩沖區,具體實現跟編譯器相關,所以不具備很好的移植性,慎用!

具體情況可參考該網站的具體說明!

C++ 大多數人將 cin::sync() 視為清除緩存區函數的誤用