C ++-标准输入循环

问题描述 投票:0回答:1

Stroustrup的使用C ++的编程原理和实践(2e,第10章,打印6)给出了以下惯用法-进行了少许修改以使其独立且可编译-用于从输入流中迭代读取直到任一EOF或遇到指定的终止符,并为其他任何停止条件引发异常。

#include <iostream>
#include <stdexcept>

int main()
{
    std::istream& is = std::cin;
    char term = '|';  // terminator

    for (int x; is >> x; ) {
        // do something with x
    }
    if (is.bad()) {
        throw std::runtime_error("bad input stream");
    }
    if (is.fail()) {
        is.clear();
        char c;
        if (!(is >> c && c == term)) {
            throw std::runtime_error("bad termination of input");
        }
    }
    // carry on: we found EOF or terminator
}

程序注释和周围的说明暗示,EOF是此迭代读取结束的可接受的(无错误的)方式。但是,当我在诸如以下不包含终止符的两行文本文件的文件上对此进行测试时,

3 1 4 1 5
9 2 6 5 3

引发异常(“输入的错误终止”)。我所期望的是一个例外-读取最后的“ 3”后,后续读取遇到EOF,导致流的eofbit被翻转,但读取也失败,导致故障位被翻转。这个习惯用法似乎假设eofbit和failbit是互斥的。

此惯用法是否有用,或者在处理EOF案件时是否存在逻辑错误?

c++ error-handling istream
1个回答
0
投票

根据this state referencefailbit

© www.soinside.com 2019 - 2024. All rights reserved.