我正在尝试使用以下代码从文件中读取数据。 (请注意,您需要在 GCC 上启用 C++11 功能才能进行此编译。)
#include <fstream>
typedef unsigned char byte;
int main()
{
std::string filename = "test.cpp";
std::basic_ifstream<byte> in(filename, std::basic_ifstream<byte>::in | std::basic_ifstream<byte>::binary);
in.exceptions(std::ios::failbit | std::ios::badbit);
byte buf[5];
in.read(buf, 5);
return 0;
}
但是,在读取数据时出现异常:
terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast
当调用 in.read(buf, 5)
命令时会发生这种情况。
我知道我可以通过不设置我设置的异常掩码来抑制这个异常,但这并不能解决问题,它只是掩盖了它。没有异常掩码,代码继续工作,但读取了 0 个字符。
有谁知道为什么抛出这个异常?我该如何让它消失?
最佳答案
c++ STL 只包含 char_traits 的两个特化:
struct char_traits < char >;
struct char_traits <wchar_t >;
对于发布的代码,定义char_traits<byte>
是必需的。
更多详情请参见 this SO question
关于c++ - std::basic_ifstream 抛出 std::bad_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628207/