如何在不复制的情况下获取std :: stringstream的长度

时间:2010-07-09 15:12:03

标签: c++

如何获得字符串流的字节长度。

stringstream.str().length();

会将内容复制到std :: string中。我不想复制。

或者,如果有人可以建议另一个在内存中工作的iostream,可以将其传递给另一个ostream,并且可以轻松获得它的大小,我将使用它。

2 个答案:

答案 0 :(得分:30)

假设您正在谈论ostringstreamtellp似乎可以做您想做的事。

答案 1 :(得分:4)

提供stringstream长度的解决方案,包括构造函数中提供的任何初始字符串:

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

    }
};