C++ 关于大多数人将 cin::sync() 视为清除缓存区函数的错误
百度cin::sync(),得到的绝大多数解释都是用作清除缓冲区,并声明一般与cin::clear()函数一起用达到目的。同样百度清除缓冲区的方法,也是绝大多数说用cin::sync()达到此目的。然而cin::sync()却并非是用作清除缓冲区的,所以这样用有时候不能达到我们想要的清空缓冲流的效果。
对于cin::sync,作用根据上述C++文档说明,应该为: Synchronize input buffer ,也就是 同步输入缓冲流。
注意到该网页中的例子:
// syncing input stream
#include <iostream> // std::cin, std::cout
int main () {
char first, second;
std::cout << "Please, enter a word: ";
first = std::cin.get();
std::cin.sync();
std::cout << "Please, enter another word: ";
second = std::cin.get();
std::cout << "The first word began by " << first << ‘\n‘;
std::cout << "The second word began by " << second << ‘\n‘;
return 0;
}
Possible output:
Please, enter a word: test
Please enter another word: text
The first word began by t
The second word began by t
Please enter another word: text
The first word began by t
The second word began by t
Realistic output:
Please, enter a word: text
Please, enter another word: The first word began by t
The second word began by e
Please, enter another word: The first word began by t
The second word began by e
好了,现在来好好解释下cin::sync()到底是做什么的。
为什么有时候能用来作为清空输入缓冲流的作用,但是这种做法有时候却不管用了。
首先,我们从键盘输入了text,按下回车,text进入输入缓冲流(包括回车),然后取一个字符‘t’赋给first,并从缓冲流中删除‘t’,然后进入了关键的cin::sync();
此时数据源的内容为:text(VS2017下);缓冲区的内容为:ext
通过cin::sync();同步数据源与缓冲区的内容,缓冲区的内容又变为了text
此时的流的定位位置为e,所以再次从缓冲区取内容时,是取的e而不是t
为什么在例如Devc++的编译器下,用cin::sync()就能清除缓冲区内容呢?
因为在Devc++下,数据源在把数据给缓冲区后,就清空了数据源的内容,所以在cin::sync()的同步下,缓冲区也被清空了,所以就形成了缓冲区被清空的情况
cin再次取数据时,缓冲区为空,所以又要进行从键盘(数据源)键入,然后传给缓冲区的步骤,在此步骤下,流的定位位置也被“刷新”了,所以不会出现输出e,而是输出t