gpt4 book ai didi

c++ - 使用迭代器将部分文件流读入字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:35 26 4
gpt4 key购买 nike

这是我到目前为止尝试过但没有成功的方法:

std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last( _file );
std::advance( last, _size );
return std::string( first, last );
}

我知道如何阅读整个文件。

std::string Read( std::ifstream& _file )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last();
return std::string( first, last );
}

但这不是我想做的。我得到一个空字符串。如果我在调试器中查看 first 和 last,即使在 std::advance 之后,它们也指向相同的东西。

最佳答案

您想使用迭代器有什么特别的原因吗?您可以一次性读取字节:

std::string s(_size, '\0');
_file.read(&s[0], _size);

如果你真的想使用迭代器阅读,你可以这样做:

std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last;
std::string s;
s.reserve(_size);
while (_size-- && first != last) s += *first++;
return s;
}

关于c++ - 使用迭代器将部分文件流读入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4086701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com