public member class
<istream> <iostream>

std::basic_istream::sentry

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

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

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

其解構函式沒有必需執行的操作。但實現可以利用sentry物件的構造和析構來對流執行所有輸入操作通用的附加初始化或清理操作。

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

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

此類結構為
1
2
3
4
5
6
7
8
9
class sentry {
public:
  explicit sentry (basic_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 (basic_istream& is, bool noskipws = false);
  ~sentry();
  explicit operator bool() const;
  sentry (const sentry&) = delete;
  sentry& operator= (const sentry&) = delete;
};

成員

explicit sentry (basic_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


另見