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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3213954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:20:31  来源:igfitidea点击:

How to get length of std::stringstream without copying

c++

提问by Budric

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.

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

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.

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

采纳答案by Mark B

Assuming you're talking about an ostringstreamit looks like tellpmight do what you want.

假设你在谈论一个ostringstream它看起来tellp可能会做你想做的事。

回答by BitByteDog

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;

    }
};