首页 > 代码库 > C++ 大多数人将 cin::sync() 视为清除缓存区函数的误用
C++ 大多数人将 cin::sync() 视为清除缓存区函数的误用
一百度,大多数人将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() 视为清除缓存区函数的误用