获取设置故障位的流位置 / std::ios::抛出故障
Getting the stream position where failbit was set / std::ios::failure was thrown
我需要解析一个文件并获取失败位置(如果有)。问题是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);
}
相关文章:
- std :: unordered_map分段构造函数中的故障
- 从std :: fileSystem ::路径对象的类中退出时的分割故障
- Xcode STD :: String_view Auto在全局名称空间故障处
- 使用std ::复制复制阵列时获取细分故障
- STD :: Promise Set_exception两次导致分段故障
- std :: set :: insert()分段故障
- 插入std :: basic_ostream实例化输出时的内存故障
- 获取设置故障位的流位置 / std::ios::抛出故障
- std::map 的比较器函数中的 SEG 故障/未定义行为
- 为什么std::istringstream在没有引发故障位标志的情况下生成错误的结果
- std::list::使用自定义比较器排序时出现分段故障
- STD上的SEG故障::设置整数插入
- std :: bind distaus desmentation dectructor上的分割故障
- C STD ::列表分割故障
- C SEG故障在STD :: String Destructor上,仅当传递变量时
- std::vector的函数push_back中的堰段故障
- std::advance - 仅在调试时偏移超出范围的故障
- 使用std::result_of时出现意外的SFINAE故障
- std::cout 可以设置坏位或故障位与操作员<<吗?如果是,什么时候?
- 分段故障-std::_Rb_tree