This answer shows how to write to an array with stringstream
, but can we obtain the total number of characters written? Surely the stringstream
has some information to know where to put the next character, but I don't know how to access it.
The OP of the linked question even asks this in a comment but I wanted a separate question to be sure.
I know ostrstream
has a pcount
method, unfortunately, it is deprecated.
CodePudding user response:
The std::ostrstream
class itself is deprecated.
Use std::ostringstream
instead, which has a tellp()
method.
#include <sstream>
int main()
{
char buf[1024];
std::ostringstream stream;
stream.rdbuf()->pubsetbuf(buf, sizeof(buf));
auto start = stream.tellp();
stream << "Hello " << "World " << std::endl;
auto written = stream.tellp() - start;
//...
}