Need for noskipws on stream with T=unsigned char in binary mode?

血红的双手。 提交于 2019-12-24 07:40:38

问题


I came across Reading the binary file into the vector of unsigned chars and tested the code discussed in the question.

The code of interest is below:

typedef unsigned char BYTE;

std::ifstream file(filename, std::ios::binary);
file.unsetf(std::ios::skipws);

std::vector<BYTE> vec;
vec.insert(vec.begin(),
           std::istream_iterator<BYTE>(file),
           std::istream_iterator<BYTE>());

According to Benjamin Lindley's answer at Why std::istream_iterator ignores newline characters?, istream::operator>>(char) skips white spaces. But the type above is unsigned char, and the file was opened with std::binary.

Why did the code require an explicit call to file.unsetf(std::ios::skipws) (or alternately, file >> std::noskipws)?


回答1:


The basic algorithm for >> of a string is:

1) skip whitespace
2) read and extract until next whitespace

If you use noskipws, then the first step is skipped.

After the first read, you are positionned on a whitespace, so the next (and all following) reads will stop immediatly, extracting nothing.



来源:https://stackoverflow.com/questions/21803615/need-for-noskipws-on-stream-with-t-unsigned-char-in-binary-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!