public member class
<istream> <iostream>

std::istream::sentry

class sentry;
為輸入準備流
用於在每次輸入操作之前和之後執行一系列操作的成員類

它的建構函式按以下順序對傳遞給它的流物件執行以下操作

  • 如果其內部錯誤標誌中的任何一個被設定,則函式會設定其failbit標誌並返回。
  • 如果它是一個關聯流,則函式會重新整理與之關聯的流(如果其輸出緩衝區不為空)。該類可以實現庫函式延遲此重新整理的方式,直到其關聯的流緩衝區的下一次對overflow的呼叫。
  • 如果其skipws格式標誌被設定,並且建構函式沒有將true作為第二個引數(noskipws)傳遞,則所有前導的空白字元(根據區域設定)將被提取並丟棄。如果此操作耗盡了字元源,則函式會將failbiteofbit內部狀態標誌都設定為。
在構造過程中發生失敗時,它可能會設定流的failbit標誌。

其解構函式沒有需要執行的操作。但是,實現可能會利用sentry物件的構造和析構來對流執行額外的初始化或清理操作,這些操作對所有輸入操作都是通用的。

所有執行輸入操作的成員函式都會自動構造此類的一個物件,然後對其進行求值(如果未設定狀態標誌,則返回true)。僅當此物件求值為true時,函式才會嘗試執行輸入操作(否則,它會在不執行操作的情況下返回)。在返回之前,函式會銷燬sentry物件。

格式化輸入操作operator>>會構造sentry物件,並將false作為第二個引數傳遞(這會跳過前導空白)。所有其他構造sentry物件的成員函式都將true作為第二個引數傳遞(這不會跳過前導空白)。

此類結構為
1
2
3
4
5
6
7
8
9
class sentry {
public:
  explicit sentry (istream& is, bool noskipws = false);
  ~sentry();
  operator bool() const;
private:
  sentry (const sentry&);             // not defined
  sentry& operator= (const sentry&);  // not defined
};
1
2
3
4
5
6
7
8
class sentry {
public:
  explicit sentry (istream& is, bool noskipws = false);
  ~sentry();
  explicit operator bool() const;
  sentry (const sentry&) = delete;
  sentry& operator= (const sentry&) = delete;
};

成員

explicit sentry (istream& is, bool noskipws = false);
為輸出操作準備輸出流,執行上述操作。
~sentry();
不執行任何操作(實現定義)。
explicit operator bool() const;
當物件被求值時,它會返回一個bool值,指示sentry建構函式是否成功執行了其所有任務:如果在構造過程的某個點設定了內部錯誤標誌,則此函式總是為該物件返回false

示例

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::sentry example
#include <iostream>     // std::istream, std::cout
#include <string>       // std::string
#include <sstream>      // std::stringstream
#include <locale>       // std::isspace, std::isdigit

struct Phone {
  std::string digits;
};

// custom extractor for objects of type Phone
std::istream& operator>>(std::istream& is, Phone& tel)
{
    std::istream::sentry s(is);
    if (s) while (is.good()) {
      char c = is.get();
      if (std::isspace(c,is.getloc())) break;
      if (std::isdigit(c,is.getloc())) tel.digits+=c;
    }
    return is;
}

int main () {
  std::stringstream parseme ("   (555)2326");
  Phone myphone;
  parseme >> myphone;
  std::cout << "digits parsed: " << myphone.digits << '\n';
  return 0;
}

輸出

digits parsed: 5552326


另見