簡體   English   中英

如何在不復制的情況下獲取std :: stringstream的長度

[英]How to get length of std::stringstream without copying

如何獲得字符串流的字節長度。

stringstream.str().length();

將內容復制到std :: string中。 我不想復制。

或者,如果任何人都可以建議另一個在內存中工作的iostream,可以通過寫入另一個ostream來傳遞,並且可以輕松地獲得它的大小我將使用它。

假設你正在討論一個ostringstream ,看起來似乎是tellp可以做你想要的。

提供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;

    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM