Namespaces
Variants

std::basic_istream<CharT,Traits>:: readsome

From cppreference.net
std:: streamsize readsome ( char_type * s, std:: streamsize count ) ;

从输入流中提取最多 count 个立即可用的字符。被提取的字符将存储到由 s 指向的字符数组中。

表现为 UnformattedInputFunction 。在构造并检查哨兵对象后,

  • 如果 rdbuf ( ) - > in_avail ( ) == - 1 ,则调用 setstate ( eofbit ) 且不提取任何字符。
  • 如果 rdbuf ( ) - > in_avail ( ) == 0 ,则不提取任何字符。
  • 如果 rdbuf ( ) - > in_avail ( ) > 0 ,则提取 std:: min ( rdbuf ( ) - > in_avail ( ) , count ) 个字符,并将其存储到由 s 指向首元素的字符数组的连续位置中。

目录

参数

s - 指向用于存储字符的字符数组的指针
count - 要读取的最大字符数

返回值

实际提取的字符数量。

异常

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

如果内部操作抛出异常,该异常会被捕获并设置 badbit 。如果为 badbit 设置了 exceptions() ,则异常会被重新抛出。

注释

此函数的行为高度依赖于具体实现。例如,在 std::ifstream 上使用 readsome() 会导致显著的实现差异性。某些库实现会在 std::ifstream 打开文件时立即填充底层 filebuf ,这意味着 readsome() 总能读取数据,甚至可能读取整个文件。而在其他实现中, std::ifstream 仅在调用输入操作时才从文件读取数据,这意味着在打开文件后立即调用 readsome() 将无法提取任何字符。类似地,调用 std:: cin . readsome ( ) 可能返回所有待处理的未读控制台输入,也可能始终返回零且不提取任何字符。

示例

#include <cassert>
#include <iostream>
#include <sstream>
int main()
{
    char c[10] = "*********"; // c[9] == '\0'
    // std::stringbuf 会将其整个缓冲区用于非阻塞读取
    std::istringstream input("This is sample text.");
    auto r = input.readsome(c, 5); // 读取 'This ' 并存储到 c[0] .. c[4]
    assert(r == 5);
    std::cout << c << '\n';
    r = input.readsome(c, 9); // 读取 'is sample' 并存储到 c[0] .. c[8]
    assert(r == 9);
    std::cout << c << '\n';
}

输出:

This ****
is sample

参见

提取字符块
(公开成员函数)
获取获取区域中立即可用的字符数量
( std::basic_streambuf<CharT,Traits> 的公开成员函数)