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

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

word 百度 true text imp clear please put ret

   百度cin::sync(),得到的絕大多數解釋都是用作清除緩沖區,並聲明一般與cin::clear()函數一起用達到目的。

   同樣百度清除緩沖區的方法,也是絕大多數說用cin::sync()達到此目的。

   

   然而cin::sync()卻並非是用作清除緩沖區的,所以這樣用有時候不能達到我們想要的清空緩沖流的效果。

   http://www.cplusplus.com/reference/istream/istream/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;
}

  This example demonstrates how sync behaves on certain implementations of cin, removing any unread character from the standard input queue of characters.  

  Possible output:

  

  Please, enter a word: test
  Please enter another word: text
  The first word began by t
  The second word began by t

  (因為網頁排版總出問題,以下內容用代碼格式寫:

然而我們將該例子在VS2017上實現時,卻不能得到該結果,得到的結果為:

技術分享

(打了斷點)

為什麽會這樣呢?註意該網頁中對此例子的結果前提:Possible output

好了,現在來好好解釋下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

  


如有不對,歡迎指正。

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