我的代码使用 std::streambuf::sgetc()
和 std::streambuf::sbumpc()
逐字符读取文件。这些函数返回一个 int 类型的值,如果有则表示读取的字符,如果到达文件末尾则为 EOF
。 EOF
是实现定义的,在大多数实现中为 -1。
我能否确保,无论何时读取一个字符(即,如果返回值不是 -1),返回值都在 [0 .. 255] 范围内?
最佳答案
标准不保证这一点,但假设结果是有效的char
,您可能就没问题了。 ,因为每个人都这样做。
如果您想绝对确定,请使用 std::char_traits<char>::to_char_type
转换回 char
.然后,标准保证您收到原始值,该值适合 char
.
std::streambuf
本质上是 std::basic_streambuf<char, std::char_traits<char>>
的快捷方式. sbumpc()
的整数类型和 sgetc()
返回的是 int_type
这个特征类的。
标准要求在[char.traits.typedefs/2]那个
[f]or a certain character container type
char_type
, a related container typeINT_T
shall be a type or class which can represent all of the valid characters converted from the correspondingchar_type
values, as well as an end-of-file value,eof()
. The typeint_type
represents a character container type which can hold end-of-file to be used as a return type of the iostream class member functions.
基本上,int_type
需要保存所有可能的字符,以及一个单独的 EOF 值。
这里是 std::streambuf
成员函数在 [streambuf.pub.get] 中定义:
int_type sbumpc();
Returns: If the input sequence read position is not available, returns
uflow()
. Otherwise, returnstraits::to_int_type(*gptr())
and increments the next pointer for the input sequence.
int_type sgetc();
Returns: If the input sequence read position is not available, returns
underflow()
. Otherwise, returnstraits::to_int_type(*gptr())
.
最终,它归结为您的标准库如何实现 std::char_traits<char>::to_int_type
,并且该标准对此的要求很少(参见 [char.traits.require] 中的表 56)。至少理论上可以将字符映射到原始字符的范围之外。
但是,我不知道有任何库实现实际执行此操作 - 大多数只是使用更大的整数类型,以便它们可以返回 -1
对于 EOF,但保持所有字符相同(这也可能是最有效的实现方式)。 cppreference.com explicitly mentions 是有原因的那个
a common implementation of
char_traits<char>::eof()
isreturn -1
, and a corresponding valid implementation ofchar_traits<char>::to_int_type(c)
isreturn (unsigned char)c
.
我检查过,stdlibc++ 和 libc++ 都是这样做的。不幸的是,我无法检查 MSVC,但我希望他们能做类似的事情。
关于c++ - std::streambuf::sgetc 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50182804/