ifstream运算符>>uint16_t设置故障位 [英] ifstream operator >> uint16_t sets failbit

查看:61
本文介绍了ifstream运算符>>uint16_t设置故障位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用c ++ std :: ifstream 类将二进制文件转换为一组变量.

i'm trying to ready a binary-file into a set of variables using the c++ std::ifstream class.

以下示例有效:

std::ifstream inFile;
inFile.open("example.bin");
uint8_t temp8;
uint16_t temp16;
inFile >> temp8;
inFile >> temp8;

但是如果我用一行替换最后两行

But if i replace the last two lines with one line

inFile >> temp16;

不读取任何内容,并且 inFile.fail()返回 true .

nothing is read and inFile.fail() returns true.

任何人都可以解释,为什么我不能读入16位变量?

Can anyone explain, why I can't read into a 16 bit variable?

推荐答案

从istream读取 uint16_t operator>> 重载是一种格式化的输入函数,即不读取二进制数据,而是读取字符串,并在必要时将其转换为数字(例如,使用 strtoul 或类似的符号).

The operator>> overload for reading uint16_t from istreams is a formatted input function, meaning does not read binary data, it reads a string and if necessary converts it to a number (e.g. using strtoul or similar).

http://en.cppreference.com/w/cpp/io中所述/basic_istream

类模板 basic_istream 提供对字符流的高级输入操作的支持.支持的操作包括格式化的输入(例如,整数值或用空格分隔的字符和字符串)和未格式化的输入(例如,原始字符和字符数组).

The class template basic_istream provides support for high level input operations on character streams. The supported operations include formatted input (e.g. integer values or whitespace-separated characters and characters strings) and unformatted input (e.g. raw characters and character arrays).

inFile>>temp16 尝试读取(通常)ASCII数字序列,直到第一个非数字字符,然后将该数字序列转换为数字,并且如果它适合 uint16_t 存储放在 temp16 中.如果您正在读取二进制文件,则istream可能不会找到ASCII数字序列,因此读取失败.

inFile >> temp16 tries to read a sequence of (usually) ASCII digits, up to the first non-digit character, then converts that sequence of digits to a number, and if it fits in uint16_t stores it in temp16. If you are reading from a binary file then the istream is probably not going to find a sequence of ASCII digits, so reading fails.

您需要使用未格式化的输入函数直接从文件中读取16位,而不必尝试将字符串解释为数字,例如:

You need to use an unformatted input function to read 16 bits directly from the file without trying to interpret a string as a number, like:

inFile.read(reinterpret_cast<char*>(&temp16), 2);

这篇关于ifstream运算符&gt;&gt;uint16_t设置故障位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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