Re: Is there a STL equivalent of sprintf
"WJ" <WJ@discussions.microsoft.com> wrote in message
news:4C301E65-CA9A-4BCC-BB0C-ED509778EE22@microsoft.com...
I want to convert a number (int or float) to std::string, just wondering if
there is a STL class or function can do that.
I have been using sprintf, but I have to declear char[] array, and then
set
the std::string to be the temp char[] array.
Thanks.
Hi,
I have written a safe sprintf-like function using boost:.format.
You would use it like this:
char buff[1024];
sprintf(buff) % "%d" % 5;
It works with wchar_t as well.
This function will check that there was no overflow of the buffer, and
throws an exception if there was.
If you already have a lot of sprintf's, like we do, then you can safely
change them to use this method to
improve the type safety. On the other hand, if you are writing code from
scratch, you are better off using
boost:.format directly.
Anyway, here's the beauty:
#include <boost/format.hpp> // boost::basic_format
namespace Util
{
namespace detail
{
template<class Char>
class feeder
{ };
template<class Char, std::size_t N>
class feeder<Char[N]>
{
typedef typename boost::basic_format<Char> format_type;
typedef typename std::basic_string<Char> string_type;
format_type format;
Char* buffer;
public:
feeder(Char* b)
: buffer(b)
{ }
~feeder()
{
string_type result = str(format);
if( result.size()>=N )
throw std::logic_error("buffer overflow in sprintf");
std::copy(result.begin(), result.end(), buffer);
buffer[result.size()] = 0;
}
//! Format string
format_type& operator%(const Char* c)
{
format.parse(c);
return format;
}
format_type& operator%(const string_type& s)
{
format.parse(s);
return format;
}
};
}
//!
//! Type-safe sprintf. Use like this:
//! char buff[1024];
//! sprintf(buff) % "%d" % 5;
//!
//! @param buffer Buffer to write to
//!
template<class Source>
typename detail::feeder<Source> sprintf(Source& buffer)
{
typedef typename detail::feeder<Source> Feeder;
return Feeder(buffer);
}
}