public member function
<ios> <iostream>

std::basic_ios::clear

void clear (iostate state = goodbit);
設定錯誤狀態標誌
設定流的內部錯誤狀態標誌的新值。

當前標誌值將被覆蓋:所有位都將被 state 中的位替換;如果 stategoodbit(其值為零),則所有錯誤標誌都將被清除。

如果呼叫此函式時流沒有關聯的流緩衝區,則會自動設定 badbit 標誌(無論 state 引數傳遞的值如何)。

請注意,根據傳遞給成員 exceptions 的最新設定,更改 state 可能會丟擲異常。

可以透過成員函式 rdstate 獲取當前狀態。

引數

state
型別為 ios_base::iostate 的物件,其值可以是以下狀態標誌成員常量的任意組合

iostate
(成員常量)
表示檢查狀態標誌的函式
good()eof()fail()bad()rdstate()
goodbit無錯誤(值為零 iostatetruefalsefalsefalsegoodbit
eofbit到達檔案尾falsetruefalsefalseeofbit
failbitI/O 操作的邏輯錯誤falsefalsetruefalsefailbit
badbitI/O 操作的讀/寫錯誤falsefalsetruetruebadbit
eofbitfailbitbadbit 是具有實現定義值的成員常量,可以進行組合(就像使用按位 OR 運算子一樣)。
goodbit 為零,表示其他位均未設定。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// clearing errors
#include <iostream>     // std::cout
#include <fstream>      // std::fstream

int main () {
  char buffer [80];
  std::fstream myfile;

  myfile.open ("test.txt",std::fstream::in);

  myfile << "test";
  if (myfile.fail())
  {
    std::cout << "Error writing to test.txt\n";
    myfile.clear();
  }

  myfile.getline (buffer,80);
  std::cout << buffer << " successfully read from file.\n";

  return 0;
}

在此示例中,myfile 以輸入模式開啟,但我們對其執行了輸出操作,因此設定了 failbit。然後呼叫 clear 來清除該標誌,以便對 myfile 嘗試執行其他操作,例如 getline

資料競爭

修改流物件。
併發訪問同一個流物件可能導致資料爭用。

異常安全

基本保證:如果丟擲異常,流處於有效狀態。
如果結果的錯誤狀態標誌不是 goodbit 並且成員 exceptions 已設定為丟擲該狀態,則丟擲成員型別為 failure 的異常。

另見