37

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.

1

2 Answers 2

36

Assuming you're talking about an ostringstream it looks like tellp might do what you want.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm using cplusplus.com/reference/iostream/stringstream with (std::ios_base::in | std::ios_base::out | std::ios_base::binary) constructor. tellp() works. Thanks.
Beware that tellp() won't consider the initial characters. ostringstream oss("hey"); cout << oss.tellp() << endl; will show 0 and not 3.
Does anyone know why tellp() isn't const? My size() method I'm writing should really be const, but clang doesn't like it. It says that tellp is not const. Does tellp modify the stringstream? Why should it?
Since this answer is not complete, check this link: stackoverflow.com/questions/4432793/size-of-stringstream
6

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; } }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.