名稱空間
變體
操作

std::basic_istream<CharT,Traits>::ignore

來自 cppreference.com
< cpp‎ | io‎ | basic istream
 
 
 
 
basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

從輸入流中提取並丟棄字元,直到幷包括 delim

ignore 行為類似於一個 UnformattedInputFunction。在構造並檢查 sentry 物件後,它從流中提取字元並丟棄它們,直到發生以下任一情況:

  • 輸入序列中出現檔案結束條件,在這種情況下,函式呼叫 setstate(eofbit)
  • 輸入序列中的下一個可用字元 cdelim,由 Traits::eq_int_type(Traits::to_int_type(c), delim) 確定。分隔符字元被提取並丟棄。如果 delimTraits::eof(),則此測試被停用。

目錄

[編輯] 引數

count - 要提取的字元數
delim - 停止提取的分隔字元。它也會被提取

[編輯] 返回值

*this

[編輯] 異常

如果發生錯誤(錯誤狀態標誌不是 goodbit)並且 exceptions() 設定為針對該狀態丟擲異常,則丟擲 failure

如果內部操作丟擲異常,則捕獲該異常並設定 badbit。如果為 badbit 設定了 exceptions(),則重新丟擲該異常。

[編輯] 示例

以下示例使用 ignore 跳過非數字輸入

#include <iostream>
#include <limits>
#include <sstream>
 
constexpr auto max_size = std::numeric_limits<std::streamsize>::max();
 
int main()
{
    std::istringstream input("1\n"
                             "some non-numeric input\n"
                             "2\n");
    for (;;)
    {
        int n;
        input >> n;
 
        if (input.eof() || input.bad())
            break;
        else if (input.fail())
        {
            input.clear(); // unset failbit
            input.ignore(max_size, '\n'); // skip bad input
        }
        else
            std::cout << n << '\n';
    }
}

輸出

1
2

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 172 C++98 count 的型別被錯誤地指定為 int 更正為 std::streamsize

[編輯] 另請參閱

提取字元
(公共成員函式) [編輯]
提取字元直到找到給定字元
(公共成員函式) [編輯]