istream :: read和istream :: operator >>之间的区别

And*_*nck 2 c++

这里有两段代码,我起初认为应该是等价的:

{
    std::ifstream stream("test.bin", std::ios_base::in | std::ios_base::binary);
    unsigned char count = 128;
    unsigned char read = 0;
    unsigned char scanline[128];
    long long start = stream.tellg();
    while (count--) {
        stream >> scanline[read++]; // <---- This is the only line which differs
    }
    long long end = stream.tellg();
    std::cout << end - start << "\n";
}

{
    std::ifstream stream("test.bin", std::ios_base::in | std::ios_base::binary);
    unsigned char count = 128;
    unsigned char read = 0;
    unsigned char scanline[128];
    long long start = stream.tellg();
    while (count--) {
        stream.read((char*)&scanline[read++], 1); // <---- This is the only line which differs
    }
    long long end = stream.tellg();
    std::cout << end - start << "\n";
}
Run Code Online (Sandbox Code Playgroud)

我的问题是第一个版本输出153(可能取决于输入数据)而第二个输出128(这是我所期望的).这必须与第一个版本中的数据提取方式有关,但我不明白为什么它不起作用.不应该只是打电话:

istream& operator>> (istream& is, unsigned char& ch);
Run Code Online (Sandbox Code Playgroud)

并每次移动文件一个字节?

Som*_*ude 10

如果您阅读operator>>(例如此处)的描述,那么您将看到它在读取之前跳过空白,直到它再次击中空白.空白不仅是space(0x20),还有tab(0x09)和newline(0x0a)之类的东西.

因此,如果您的二进制数据包含被视为文本文件空白的字节,那么operator>>将读取但不存储它们,这将使报告的数字偏斜tellg.