C++ 如何跟踪std::stringstream中的当前位置
我正在编写一个自定义日志程序,其中每当C++ 如何跟踪std::stringstream中的当前位置,c++,stringstream,C++,Stringstream,我正在编写一个自定义日志程序,其中每当std::stringstream足够大(以节省一些IO延迟)时,我将日志消息缓冲在std::stringstream中,并将其刷新到一个文件(std::ofstream)。由于std::stringstream没有.size()方法,我使用seekg和tellg: template <typename T> MyClass & operator<< (const T& val) { boost::unique
std::stringstream
足够大(以节省一些IO延迟)时,我将日志消息缓冲在std::stringstream
中,并将其刷新到一个文件(std::ofstream
)。由于std::stringstream
没有.size()
方法,我使用seekg
和tellg
:
template <typename T>
MyClass & operator<< (const T& val)
{
boost::unique_lock<boost::mutex> lock(mutexOutput);
output << val; //std::stringstream output;
output.seekg(0, std::ios::end);
if(output.tellg() > 1048576/*1MB*/){
flushLog();
}
return *this;
}
模板
MyClass&operator您可以使用ostringstream::tellp()
获取字符串的长度。这里有一个例子摘自
#包括
#包括
int main()
{
std::ostringstream s;
std::cout fstream已经提供了缓冲。您是否测试过使用stringstream实际上会加快速度?如果您想要更大的fstream缓冲区,为什么不尝试自定义fstream缓冲区的大小?另外,不要使用endl和fstream,而是使用“\n”,因为它不会强制刷新。我怀疑stringstream
的tellg()
涉及一些简单的指针算法,所以它不应该太昂贵。但是,正如尼尔·柯克指出的,您可能应该只依赖fstream
的缓冲。无论何时谈论性能,都要进行测量。
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream s;
std::cout << s.tellp() << '\n';
s << 'h';
std::cout << s.tellp() << '\n';
s << "ello, world ";
std::cout << s.tellp() << '\n';
s << 3.14 << '\n';
std::cout << s.tellp() << '\n' << s.str();
}
0
1
13
18
hello, world 3.14