ps:我发现有网站将我之前写的标题为: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
所以实现上,可不一定能清空缓冲区,具体实现跟编译器相关,所以不具备很好的移植性,慎用!
具体情况可参考该网站的具体说明!