0

I am putting some data into a stream buf obtained from stringstream

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

What I want is to be able to put some dummy data into this buffer and then at a later time, once I have the correct data, replace the dummy data.

Something on these lines:

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

I tried using pubseekpos + sputn but it doesnt seem to be working as expected. Any ideas what could be the correct way to do this?

Arun
  • 3,138
  • 4
  • 30
  • 41

2 Answers2

3

Just use data.seekp(pos); then data.write() - you shouldn't need to stuff around with the buffer at all.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

This may help you to get started, it writes some number of X's and prints them back, which can also be done via 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;
}
perreal
  • 94,503
  • 21
  • 155
  • 181