Lor*_*ins 8 c++ stringstream c++11
鉴于strstream有以下构造函数:
strstream( char* s, int n, std::ios_base::openmode mode);
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以直接在“只读”模式下使用标准字符串底层的缓冲区,以避免缓冲区重新分配产生奇怪的副作用:
std::string buffer("Dummy Data");
std::strstream ss(
const_cast<char *>(buffer.data()), buffer.length(), std::ios_base::in);
std::string other;
ss >> other;
std::cout << other << std::endl;
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,上面的代码最终生成了other一个空字符串。在文档中有一个示例,其中C 数组用作 的静态缓冲区strstream,所以我想知道它不能使用缓冲区内容的原因是什么std::string?
注意:我无法使用,std::stringstream因为相关平台的 VS 实现仅限于 4GB 大小,如此处所述
更新:
我发现使用std::ios_base::app(如示例中所示)几乎可以使我的代码正常工作。现在最大的问题(根据我收到的评论)是它strstream已被长期弃用。也许boost iostreams中有一些东西可以提供帮助,但我不太了解该库。
您可以使用Boost 作为替代方案strstream,如下所示:stringstreambufferstream
#include <iostream>
#include <boost/interprocess/streams/bufferstream.hpp>
namespace bi = boost::interprocess;
int main()
{
std::string buffer("Dummy Data");
bi::bufferstream ss(&buffer[0], buffer.size());
std::string other;
ss >> other;
std::cout << other << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个类似乎只是头文件,所以不需要编译boost。无论如何,如果使用 Visual Studio,您可以使用vcpkg轻松安装 boost。
注意:正如 Peppin 对这个问题的评论中提到的,如果您的数据源自文件,那么这将是一个更好的方法,而不是将其完全读入内存而仅使用内存映射文件。这个答案中有一个很好的例子来说明如何做到这一点。
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |