std::basic_streambuf<CharT,Traits>::setg

来自cppreference.com
< cpp‎ | io‎ | basic streambuf
 
 
 
 
protected:
void setg( char_type* gbeg, char_type* gcurr, char_type* gend );

设置定义获取区的指针值。

调用后,eback() == gbeggptr() == gcurregptr() == gend 都是 true

如果 [gbeggend)[gbeggcurr)[gcurrgend) 不是有效范围,那么行为未定义。

参数

gbeg - 指向获取区新起始的指针
gcurr - 指向获取区中新的当前字符的指针(获取指针
gend - 指向获取区新结尾的指针

示例

#include <iostream>
#include <sstream>
 
class null_filter_buf : public std::streambuf
{
    std::streambuf* src;
    char ch; // 单字节缓冲区
protected:
    int underflow()
    {
        traits_type::int_type i;
        while ((i = src->sbumpc()) == '\0')
            ; // 跳过零
        if (!traits_type::eq_int_type(i, traits_type::eof()))
        {
            ch = traits_type::to_char_type(i);
            setg(&ch, &ch, &ch+1); // 使得一个读取位置可用
        }
        return i;
    }
public:
    null_filter_buf(std::streambuf* buf) : src(buf)
    {
        setg(&ch, &ch + 1, &ch + 1); // 缓冲区初始为满
    }
};
 
void filtered_read(std::istream& in)
{
    std::streambuf* orig = in.rdbuf();
    null_filter_buf buf(orig);
    in.rdbuf(&buf);
    for (char c; in.get(c);)
        std::cout << c;
    in.rdbuf(orig);
}
 
int main()
{
    char a[] = "This i\0s \0an e\0\0\0xample";
    std::istringstream in(std::string(std::begin(a), std::end(a)));
    filtered_read(in);
}

输出:

This is an example

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 4023 C++98 setg 不要求输入序列是有效范围 要求有效

参阅

重定位输出序列的起始、下一位置和终止指针
(受保护成员函数)