- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试使用以下代码从文件中读取数据。 (请注意,您需要在 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/
这是我第一次使用QString,我不知道如何解决此错误: Personanetscape.cpp:16:错误:没有匹配的函数可以调用“std::basic_ifstream::basic_ifstre
我正在尝试编写一个程序来打开一个文件并计算该文件中以空格分隔的单词数。 #include #include #include using namespace std; int main() {
从这段代码构建的程序: #include using std::basic_ifstream; #include using std::streamsize; #include using Ze
我有一个二进制文件。上半部分存储了2288*2288个经度浮点值,同样数量的纬度浮点值占据了下半部分。我使用以下代码将它们加载到浮点 vector 中。它可以像魅力一样运行,但给了我不正确的结果。关于
我应该编写一个程序,合并两个文件中的数字并将所有数字写入第三个文件。该程序从两个不同的文件中获取输入并将其输出写入第三个文件。每个输入文件都包含一个按从小到大排序的 int 类型数字列表。程序运行后,
这可能吗?我一直在尝试读取一个包含俄语的简单文件,但显然无法正常工作。 我调用了 file.imbue(loc)(此时,loc 是正确的,Russian_Russia.1251)。而 buf 的类型是
我正在尝试使用以下代码从文件中读取数据。 (请注意,您需要在 GCC 上启用 C++11 功能才能进行此编译。) #include typedef unsigned char byte; int m
我想不通,是否可以将 std::basic_ifstream 和 std::basic_ofstream 与 std::basic_filebuf 的自定义实现一起使用? 按 64KB 大小的 blo
我在图像处理的上下文中学习 IO,这是我第一次不得不将流用于二进制文件而不是格式化/文本文件。我正在尝试使用带有模板编程的重载流插入运算符将位图的前 14 个字符读入结构。 #include #in
以下代码按预期工作。源代码,文件“file.txt”和“out.txt”都是用utf8编码的。但是当我改变时它不起作用wchar_t至 char16_t在 main() 的第一行.我用 -std=c+
以下代码按预期工作。源代码、文件“file.txt”和“out.txt”都是用utf8编码的。但是,当我在 main() 的第一行将 wchar_t 更改为 char16_t 时,它不起作用。我已经用
当我尝试运行它时: #include #include int _tmain(int argc, TCHAR *argv[]) { std::basic_ifstream file("Te
There are already questions在 Stackoverflow 上询问 为什么 basic_fstream不起作用。答案说char_traits仅专门用于 char和 wchar
上面写着“Apple Mach-O Linker (Id) Error "readIt(std::_1::basic_ifstream >&," 有没有人看到它一直卡住的错误?非常感谢! #inclu
我是一名优秀的程序员,十分优秀!