c++ - 获取设置 failbit 的流位置/std::ios::failure 被抛出

标签 c++ stream position

我需要解析一个文件并获取失败位置(如果有的话)。问题是如果设置了 failbittellg() 就没用了。

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

更新

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

最佳答案

你只需要清除流,这样你就可以使用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 I'已经测试过,但我还没有确定这是否有保证)。

关于c++ - 获取设置 failbit 的流位置/std::ios::failure 被抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002153/

相关文章:

Java缓冲区和流: Releasing underlying resources

android - 如何通过 USB 将 Android 应用程序与 PC 上的 C++ 程序连接起来

jquery - 如何: Sliding from one background image to another 100% height and width

android - 如何在 Android 上的 EditText 中的字符之间插入文本?

c++ - 链表c++代码错误

c++ - 开罗翻转绘图

c++ - 与普通 cout 的行为相比,为什么 c++ 中的 for 循环访问未初始化的内存位置?

c++ - 如何为模板化类型提供模板函数的特化?

java - 使用线程从InputStream读取数据

css - "position:fixed"不适用于标题菜单