How can I get the length in bytes of a stringstream.
stringstream.str().length();
would copy the contents into std::string. I don't want to make a copy.
Or if anyone can suggest another iostream that works in memory, can be passed off for writing to another ostream, and can get the size of it easily I'll use that.
Assuming you're talking about an ostringstream
it looks like tellp
might do what you want.
A solution that provides the length of the stringstream including any initial string provided in the constructor:
#include <sstream>
using namespace std;
#ifndef STRINGBUFFER_H_
#define STRINGBUFFER_H_
class StringBuffer: public stringstream
{
public:
/**
* Create an empty stringstream
*/
StringBuffer() : stringstream() {}
/**
* Create a string stream with initial contents, underlying
* stringstream is set to append mode
*
* @param initial contents
*/
StringBuffer(const char* initial)
: stringstream(initial, ios_base::ate | ios_base::in | ios_base::out)
{
// Using GCC the ios_base::ate flag does not seem to have the desired effect
// As a backup seek the output pointer to the end of buffer
seekp(0, ios::end);
}
/**
* @return the length of a str held in the underlying stringstream
*/
long length()
{
/*
* if stream is empty, tellp returns eof(-1)
*
* tellp can be used to obtain the number of characters inserted
* into the stream
*/
long length = tellp();
if(length < 0)
length = 0;
return length;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With