Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get length of std::stringstream without copying

Tags:

c++

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.

like image 348
Budric Avatar asked Jul 09 '10 15:07

Budric


2 Answers

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

like image 62
Mark B Avatar answered Oct 14 '22 11:10

Mark B


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;

    }
};
like image 30
BitByteDog Avatar answered Oct 14 '22 10:10

BitByteDog