获取设置故障位的流位置 / std::ios::抛出故障

Getting the stream position where failbit was set / std::ios::failure was thrown

本文关键字:故障 std ios 位置 设置 获取      更新时间:2023-10-16

我需要解析一个文件并获取失败位置(如果有)。问题是tellg()如果设置了failbit则毫无用处。

有没有一种优雅的(内置的?)方法来找到failbit设置的位置?

UPD

使用clear()tellg()有效吗?我找不到流的状态(包括位置)是否保证在失败后保持有效

您只需要clear流,以便可以使用tellg()

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
    std::ifstream infile("input.txt");
    std::vector<int> data{ std::istream_iterator<int>(infile), {} };
    infile.clear();
    std::cout << "failed at position: " << infile.tellg();
}

当然,这仅适用于一开始就支持tellg(有意义)的流。例如,如果您尝试将其与std::cin一起使用而不是fstream,您将不会得到有意义的结果(使用我测试过的编译器返回 -1,但我不确定这是否得到保证)。

如果在处理异常时流已超出范围,则无法执行。如果流仍在范围内,则可以clear故障位,然后根据需要使用 setstate 重置故障位。

例:

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream test("10 20 thirty 40 50");
    test.exceptions(std::istream::failbit);
    try
    {
        int val;
        while (test >> val)
        {
        }
    }
    catch (...)
    {
        std::cout << "Went boom.n";
    }
    test.clear();
    std::cout << test.tellg();
    // test.setstate(std::ios::failbit);
}