stringstream缓冲区操作

std::stringstream buffer manipulation

本文关键字:操作 缓冲区 stringstream      更新时间:2023-10-16

我正在将一些数据放入流中,但从stringstream

获得
std::stringstream data;
auto buf = data.rdbuf();
buf->sputn(XXX);

我想要的是能够把一些虚拟数据放入这个缓冲区,然后在以后的时间,一旦我有正确的数据,替换虚拟数据。

下面这些行:

auto count = 0;
buf->sputn((unsigned char *)&count, sizeof(count));
for (/*some condition*/)
{
   // Put more data into buffer
   // Keep incrementing count
}
// Put real count at the correct location

我尝试使用pubseekpos + sputn,但它似乎不像预期的那样工作。有什么正确的方法吗?

只使用data.seekp(pos);然后data.write() -你根本不需要填充缓冲区

这可以帮助您开始,它写入一些X并将它们打印回来,这也可以通过data << 'X':

来完成。
#include <sstream>
#include <iostream>
int main() {
    std::stringstream data;
    auto buf = data.rdbuf();
    char c;
    for (int count = 0; count < 10; count++) {
        buf->sputn("X", 1); 
    }   
    while (data >> c) {
        std::cout << c;
    }   
    return 0;
}