C++ seekg不';将istream与自定义streambuf一起使用时不起作用
我试图使用流来读取现有数据的向量C++ seekg不';将istream与自定义streambuf一起使用时不起作用,c++,C++,我试图使用流来读取现有数据的向量 // http://stackoverflow.com/questions/8815164/c-wrapping-vectorchar-with-istream template<typename CharT, typename TraitsT = std::char_traits<CharT> > class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT>
// http://stackoverflow.com/questions/8815164/c-wrapping-vectorchar-with-istream
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT>
{
public:
vectorwrapbuf(std::vector<CharT> &vec)
{
this->setg(&vec[0], &vec[0], &vec[0] + vec.size());
}
};
int main()
{
vector<char> data(100, 1);
vectorwrapbuf<char> databuf(data);
std::istream file(&databuf);
file.exceptions(std::istream::failbit | std::istream::badbit);
file.seekg(10); // throws
}
//http://stackoverflow.com/questions/8815164/c-wrapping-vectorchar-with-istream
模板
类vectorwrapbuf:public std::basic_streambuf
{
公众:
vectorwrapbuf(标准::vector&vec)
{
此->设置(&vec[0]、&vec[0]、&vec[0]+vec.size());
}
};
int main()
{
矢量数据(100,1);
vectorwrapbuf-databuf(数据);
std::istream文件(&databuf);
异常(std::istream::failbit | std::istream::badbit);
file.seekg(10);//抛出
}
但是,当我调用seekg
时,它会抛出一个异常(如果不使用异常,则通常会报告错误)。为什么会这样?10在输入数据的100个字符范围内
代码需要同时使用C++11和之前的编译器
实例:
std::basic\u streambuf::seekpos
默认情况下,根据
istream::seekg()
以便将其作为错误条件,因此您需要在类中重写该函数vectorwrapbuf
并返回实际位置。好的,谢谢。你能建议我怎么做吗?还是不简单?@NeilKirk看起来你需要验证输入,用正确的位置调用setg()
,然后返回第一个参数。