Chr*_*ris 5 c++ io file-io ifstream c++11
我正在尝试使用以下代码从文件中读取数据。(请注意,您需要在 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;
}
Run Code Online (Sandbox Code Playgroud)
但是,在读取数据时出现异常:
抛出“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 >;
Run Code Online (Sandbox Code Playgroud)
对于发布工作的代码,char_traits<byte>需要定义。
这个SO问题中的更多细节
| 归档时间: |
|
| 查看次数: |
1316 次 |
| 最近记录: |