c++ - std::streambuf::sgetc 的范围

标签 c++ stl

我的代码使用 std::streambuf::sgetc()std::streambuf::sbumpc() 逐字符读取文件。这些函数返回一个 int 类型的值,如果有则表示读取的字符,如果到达文件末尾则为 EOFEOF 是实现定义的,在大多数实现中为 -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 type INT_­T shall be a type or class which can represent all of the valid characters converted from the corresponding char_­type values, as well as an end-of-file value, eof(). The type int_­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, returns traits​::​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, returns traits​::​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() is return -1, and a corresponding valid implementation of char_traits<char>::to_int_type(c) is return (unsigned char)c.

我检查过,stdlibc++ 和 libc++ 都是这样做的。不幸的是,我无法检查 MSVC,但我希望他们能做类似的事情。

关于c++ - std::streambuf::sgetc 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50182804/

相关文章:

c++ - 返回指向局部变量的指针总是未定义的行为

c++ - 为什么不能在 C++ 中创建一个包含一个元组和一个 unique_ptr 作为值的元组?

c++ - 为什么这一行不编译?

c++ - const vector 中的非常量

c++ - 通过返回迭代器隐藏 STL 容器实现

c++ - 使用 CryptoPP 库加密和解密字节数组/vector

c++ - 如何将一对迭代器转换为 View ?

c++ - 磁盘调度程序 SCAN 算法错误

java - 如何在Java上检索显卡信息?

c++ - STL Map<string, > 与 LLVM 库冲突