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

Bud*_*ric 31 c++

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

stringstream.str().length();
Run Code Online (Sandbox Code Playgroud)

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

或者,如果任何人都可以建议另一个在内存中工作的iostream,可以通过写入另一个ostream来传递,并且可以轻松地获得它的大小我将使用它.

Mar*_*k B 32

假设你正在谈论ostringstream它看起来tellp可能会做你想要的.

  • 请注意`tellp()`不会考虑初始字符.`ostringstream oss("嘿"); cout << oss.tellp()<< endl;`将显示`0`而不是`3`. (20认同)
  • 有谁知道为什么`tellp()`不是const?我写的`size()`方法应该是const,但是clang不喜欢它.它说`tellp`不是常量.`tellp`是否会修改`stringstream`?为什么要这样? (3认同)

Bit*_*Dog 5

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

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

    }
};
Run Code Online (Sandbox Code Playgroud)