std :: basic_ifstream throws std :: bad_cast [英] std::basic_ifstream throws std::bad_cast

查看:620
本文介绍了std :: basic_ifstream throws std :: bad_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用下面的代码从文件中读取数据。 (注意,您需要在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;但是,当读取数据时,我得到一个例外:

在抛出'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& code>是必需的。



有关此SO问题


I am trying to read data from a file using below code. (Note that you need to enable C++11 features on GCC to make this compile.)

#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;
}

However, when reading data I get an exception:

terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast

This happens when the in.read(buf, 5) command is invoked.

I know that I can suppress this exception by not setting the exception mask I set but this does not fix the problem, it only masks it. Without an exception mask, the code keeps working but 0 characters are read.

Does anyone know why this exception is thrown? And how do I make it go away?

解决方案

c++ STL only contains two specializations of char_traits:

   struct char_traits < char >;
   struct char_traits <wchar_t >;

For the code posted to work a definition of char_traits<byte> is required.

More details in this SO question

这篇关于std :: basic_ifstream throws std :: bad_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆