0

这是我第一次发帖,请多多包涵。

我有一个文件,我需要通过重定向读取标头,并且我正在使用 cin 来捕获字节并存储它们以供以后使用。

该文件的 hexdump 是:

42 02 02 02 ff 0a 00 00  00 19 00 00 00 ff

是)我有的:

char magic, cs1, cs2, cs3, selector;
char temp1, temp2, temp3, temp4;
cin >> magic;
cin >> cs1;
cin >> cs2;
cin >> cs3;
cin >> selector; 
//   
cin >> temp1;
cin >> temp2;
cin >> temp3;
cin >> temp4;

前5个字节代表magicNumber、channelSize、channelSize、channelSize、selectorBit。接下来的 4 个字节是一个宽度值,在 LSB 到 MSB 中分成 4 个字节。

当我在 0a 上使用 cin 时,它是十六进制的 10(我想要的值),它会将其读取为换行符并因此跳过它。

cout << temp1 << endl;
cout << temp2 << endl;
cout << temp3 << endl;
cout << temp4 << endl;

这将包含(十六进制):

0
0
0
19

cin 跳过 0a 并获取下一个值。有没有办法强制它读取 0a?

如果需要更多信息,请告诉我。谢谢

——凯尔

4

2 回答 2

2

这是因为cin, which is anistream期望数据是文本。

如果您正在使用二进制数据istream::get,那么istream::read这就是您正在寻找的东西。

std::cin.get(temp1)
std::cin.get(temp2)
std::cin.get(temp3)
std::cin.get(temp4)

从输入流中检索四个字节的值。

char buff[4];
std::cin.read(buff, 4);

将为您将数据块读入一个字符数组。如果字节序与数据的字节序匹配,则可以使用纯整数。

于 2012-04-27T07:26:41.373 回答
0

There are two problems with your code. The first is that you're using >> to read binary data; >> is for reading formatted text data. (In particular, the first thing >> does is skip white space.) The second is that you're trying to read binary data from cin. This is undefined behavior, because cin is opened in text mode. On systems where the two are identical (Unix), it will work, but on others, you may encounter various surprises. (The exact data you show will probably work under Windows as well, depending on the library implementation, but other binary data will fail: 0x1A will generally cause an end of file, 0x0D will disappear if followed by a 0x0A, etc. And an implementation could reasonably remove null bytes from a text stream.)

于 2012-04-27T07:47:01.550 回答