【发布时间】:2014-11-21 11:11:01
【问题描述】:
我有一个包含十六进制文本的文件,我想使用 std::fstream 将其作为二进制缓冲区读取
示例文件:
hex.txt
00010203040506070809
读取这个应该会导致读取从 0 到 9 的数字。
但是下面的代码并没有做我想要的。
using std::ifstream;
int main(int argc, char *argv[])
{
ifstream hexfile("hex.txt");
unsigned char c;
while (hexfile >> std::hex >> std::setw(2) >> c) {
printf ("got %u\n",c); //print as binary, not as char
}
hexfile.close();
return 0;
}
输出:
got 48
got 48
got 48
got 49
got 48
got 50
got 48
got 51
got 48
got 52
got 48
got 53
got 48
got 54
got 48
got 55
got 48
got 56
got 48
got 57
有趣的是,替换 unsigned char c;带无符号整数 c; 不会打印任何内容(即使在第一次读取时文件流也可能返回 false)
我做错了什么? std::hex 应该确保输入被解释为十六进制 std::setw(2) 应该确保每次迭代都读取 2 个字符
【问题讨论】: