public member function
<istream> <iostream>

std::basic_istream::peek

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

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

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

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

引數



返回值

輸入序列中的下一個字元,使用成員 traits_type::to_int_type 轉換為 int_type 型別的值。
成員型別int_type是能夠表示任何字元值或特殊*檔案結束*符的整型。

如果輸入序列中沒有更多字元可供讀取,或者設定了任何內部狀態標誌,則該函式返回檔案結束值(traits_type::eof()),並保留相應的內部狀態標誌

標誌錯誤
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
30
// basic_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
  std::istream::int_type c;
  c = std::cin.peek();  // peek character

  if ( c == std::char_traits<char>::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


資料競爭

修改流物件。
對同一流物件的併發訪問可能導致資料爭用,但標準流物件 cinwcin 當它們與 stdio 同步時除外(在這種情況下,不會產生資料爭用,儘管不保證讀取的字元歸屬到哪個執行緒)。

異常安全

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

另見