istream :: ignore()如何工作? [英] How does istream::ignore( ) work?

查看:322
本文介绍了istream :: ignore()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读关于istream :: ignore()的这里 。我想我得到的功能的主要想法,但我看到了一些例子只接受使用此函数的数字输入,我不知道为什么它会工作。

I've been reading about istream::ignore( ) here. I think I get the main idea of the function it does, but I've seen some examples of accepting only numeric input that uses this function, and I'm not sure why it works.

为什么这个代码会忽略除数字输入之外的所有东西?

Why would this code ignore everything except numeric input?

#include <iostream>
#include <sstream>
#include <limits>

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(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
        } else {
            std::cout << n << '\n';
        }
    }
}



我以为istream:

I had thought that istream::ignore( ) would ignore any and all characters specified by a certain number until the delimiter..

推荐答案

当<$ c $时,忽略()会忽略某个数字指定的任何和所有字符,直到分隔符。 c> input>> n; 遇到非数字输入,它设置 fail 标志。代码检查是否设置( if(input.fail())),如果是,则忽略 numeric_limits< streamsize> ;: :max()字符,直到它命中换行符 \\\
字符。实际上,这意味着遇到失败的行的其余部分将被忽略。

When input >> n; encounters non-numeric input, it sets the fail flag. The code checks whether it is set (if (input.fail())), and if it is, ignores up to numeric_limits<streamsize>::max() characters, until it hits a newline \n character. Effectively, this means that the rest of the line on which the failure was encountered will be ignored.

请注意,这仍然会读取一行开头的数字,如25 asdasf。然而,如果行是25 asdfasf 26,则将读取25,但随后将发生故障,并忽略该行的其余部分,包括26结束。

Note that this will still read a number at the beginning of a line like "25 asdasf". If the line is "25 asdfasf 26", however, the 25 will be read, but then the failure occurs and the rest of the line is ignored, including the 26 at the end.

这篇关于istream :: ignore()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆