为什么要单独做C++字符串格式化?
C++中可以使用stringstream来格式化字符串如下:
stringstream sstream;
sstream << "I have made " << 500 << " dollars on this product.";
string formated_str = sstream.str();
但是,这种方式并不好用。有没有类似printf操作的方式呢?在opencv中有类似的封装。
怎么做?
怎么用?
string formated_str = format("I have made %d dollars on this product.", 500);
怎么封装的?
typedef std::string String;
int cv_vsnprintf(char* buf, int len, const char* fmt, va_list args)
{
#if defined _MSC_VER
if (len <= 0) return len == 0 ? 1024 : -1;
int res = _vsnprintf_s(buf, len, _TRUNCATE, fmt, args);
// ensure null terminating on VS
if (res >= 0 && res < len)
{
buf[res] = 0;
return res;
}
else
{
buf[len - 1] = 0; // truncate happened
return res >= len ? res : (len * 2);
}
#else
return vsnprintf(buf, len, fmt, args);
#endif
}
String format( const char* fmt, ... )
{
AutoBuffer<char, 1024> buf;
for ( ; ; )
{
va_list va;
va_start(va, fmt);
int bsize = static_cast<int>(buf.size());
int len = cv_vsnprintf(buf.data(), bsize, fmt, va);
va_end(va);
CV_Assert(len >= 0 && "Check format string for errors");
if (len >= bsize)
{
buf.resize(len + 1);
continue;
}
buf[bsize - 1] = 0;
return String(buf.data(), len);
}
}
//! @addtogroup core_utils
//! @{
/** @brief Automatically Allocated Buffer Class
The class is used for temporary buffers in functions and methods.
If a temporary buffer is usually small (a few K's of memory),
but its size depends on the parameters, it makes sense to create a small
fixed-size array on stack and use it if it's large enough. If the required buffer size
is larger than the fixed size, another buffer of sufficient size is allocated dynamically
and released after the processing. Therefore, in typical cases, when the buffer size is small,
there is no overhead associated with malloc()/free().
At the same time, there is no limit on the size of processed data.
This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
the number of stack-allocated elements. Here is how the class is used:
\code
void my_func(const cv::Mat& m)
{
cv::AutoBuffer<float> buf(1000); // create automatic buffer containing 1000 floats
buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
// otherwise the buffer of "m.rows" floats will be allocated
// dynamically and deallocated in cv::AutoBuffer destructor
...
}
\endcode
*/
//! @} core_utils