public member function
<istream> <iostream>

std::istream::peek

int peek();
窺視下一個字元
在不提取它的情況下返回輸入序列中的下一個字元:該字元保持為要從流中提取的下一個字元。

如果在呼叫之前已設定了任何內部狀態標誌,或者在呼叫過程中設定了,則函式返回檔案結束值(EOF)。

在內部,該函式透過首先構造一個sentry物件(將noskipws設定為true)來訪問輸入序列。然後(如果good),它透過呼叫其成員函式sgetc從其關聯的流緩衝區物件中讀取一個字元,最後在返回之前銷燬sentry物件。

呼叫此函式會將gcount的返回值設定為零。

引數



返回值

輸入序列中的下一個字元,型別為int

如果沒有更多字元可從輸入序列中讀取,或者設定了任何內部狀態標誌,則函式返回檔案結束值(EOF),並留下正確的內部狀態標誌設定。

flagerror
eofbit由於輸入序列中沒有可用字元(已達到檔案結尾),因此無法窺視字元。
failbit構造sentry失敗(例如,當流狀態在呼叫之前不是good時)。
badbit流錯誤(例如,當此函式捕獲由內部操作丟擲的異常時)。
設定時,流的完整性可能受到影響。
一次操作可能設定多個標誌。

如果操作設定了一個已與成員exceptions註冊的內部狀態標誌,則該函式將丟擲成員型別為failure的異常。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// istream::peek example
#include <iostream>     // std::cin, std::cout
#include <string>       // std::string
#include <cctype>       // std::isdigit

int main () {

  std::cout << "Please, enter a number or a word: ";
  std::cout.flush();    // ensure output is written

  std::cin >> std::ws;  // eat up any leading white spaces
  int c = std::cin.peek();  // peek character

  if ( c == EOF ) return 1;
  if ( std::isdigit(c) )
  {
    int n;
    std::cin >> n;
    std::cout << "You entered the number: " << n << '\n';
  }
  else
  {
    std::string str;
    std::cin >> str;
    std::cout << "You entered the word: " << str << '\n';
  }

  return 0;
}

可能的輸出
Please, enter a number or a word: foobar
You entered the word: foobar


資料競爭

修改流物件。
對同一流物件的併發訪問可能會導致資料爭用,除了標準流物件cin當它與stdio同步時(在這種情況下,不會引發資料爭用,儘管不對讀取的字元歸因於執行緒的順序做任何保證)。

異常安全

基本保證:如果丟擲異常,物件處於有效狀態。
如果結果錯誤狀態標誌不是goodbit且成員exceptions設定為針對該狀態進行丟擲,則它會丟擲成員型別為failure的異常。
任何由內部操作丟擲的異常都將被函式捕獲並處理,設定badbit。如果badbit在最後一次呼叫exceptions時被設定,則該函式將重新丟擲捕獲到的異常。

另見