Ответ 1
Предполагая, что вы говорите о ostringstream
, похоже, что tellp
может делать то, что вы хотите.
Как я могу получить длину в байтах строкового потока.
stringstream.str().length();
скопирует содержимое в std::string. Я не хочу делать копию.
Или, если кто-то может предложить другой iostream, который работает в памяти, может быть передан для записи в другой ostream и может легко получить его размер, я буду использовать его.
Предполагая, что вы говорите о ostringstream
, похоже, что tellp
может делать то, что вы хотите.
Решение, которое обеспечивает длину строкового потока, включая любую начальную строку, предоставленную в конструкторе:
#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;
}
};