Namespaces
Variants

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

From cppreference.net
basic_istream & ignore ( std:: streamsize count = 1 , int_type delim = Traits :: eof ( ) ) ;

从输入流中提取并丢弃字符,直至遇到并包括 delim 为止。

ignore 的行为类似于 无格式输入函数 。在构造并检查哨兵对象后,它会从流中提取字符并丢弃它们,直到满足以下任一条件:

  • 输入序列中出现文件结束条件,此时函数会调用 setstate ( eofbit )
  • 输入序列中的下一个可用字符 c delim (由 Traits :: eq_int_type ( Traits :: to_int_type ( c ) , delim ) 确定)。该分隔符将被提取并丢弃。若 delim Traits :: eof ( ) 则禁用此检测。

目录

参数

count - 要提取的字符数量
delim - 用于停止提取的分隔字符。该字符也会被提取

返回值

* this

异常

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

如果内部操作抛出异常,该异常会被捕获并设置 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

参见

提取字符
(公开成员函数)
提取字符直到发现指定字符
(公开成员函数)