我正在嘗試使用下面的代碼從文件中讀取數據。 (請注意,您需要啓用GCC C++ 11層的功能,使這個編譯)std :: basic_ifstream引發std :: bad_cast
#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個字符。
有誰知道爲什麼拋出這個異常?我該如何讓它消失?
對我來說更多細節,它甚至不編譯:'沒有匹配的構造函數的「的std :: basic_ifstream' –
2013-07-13 08:00:09
@ H2CO3正如介紹中陳述初始化,您需要啓用C + +11。否則,'basic_ifstream'的構造函數不存在。另一種修正:使用'filename.c_str()'而不是'filename'。 – Chris
此問題已在此解決:http://stackoverflow.com/q/19205531/331024它具有char_traits的完整實現和codecvt –