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

< cpp‎ | io‎ | basic streambuf
 
 
 
 
void setg( char_type* gbeg, char_type* gcurr, char_type* gend );

设置定义获取区的指针值。特别是调用后 eback() == gbeggptr() == gcurregptr() == gend

参数

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::not_eof(i)) {
            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

参阅

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