如何获得的std stringstream的长度不复制 std:string可不可以在初始化以后复制指定长度的字符串

作者&投稿:堂军 (若有异议请与网页底部的电邮联系)
一个解决方案,它提供了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;
}
};

C++的std::stringstream,stringBuffer的区别~

不是stringstream很方便,而是STL很方便.不要前面使用stringstream,后面使用C函数.
你这里stringstream是多余的.可以
ofstream of( pszFilename ) ;
of <<a<<b<<"aaaaa"<<"aaaa".....(子子孙孙无穷尽也); //这里的数据已经到文件了.没必要中间插个stringstream.
stringstream是弥补输入设备(CIN), 输出设备(COUT),外围设备(fstream)在内存设备上数据格式化上的空缺. 但是某块内存也需要这样方便的IO操作,我们可以直接定义自己的stream_buf类,进行直接的重载> 等操作符,而像fstream那样省去stringstream.
所以C++是很变态很强大的东西,它本身的特征加上STL和boost库.让它成为最"高级",而却支持最低级的操作(_asm{},指针). 加油吧.C++编程会你带来惊喜的.

string.c_str()这是string的数据保存区,可以操作它。不过你不知道它的空间够不够,如果不用构造函数,非常容易内存操作出错

string.c_str()这是string的数据保存区,可以操作它。不过你不知道它的空间够不够,如果不用构造函数,非常容易内存操作出错