Kai-Uwe Bux
10/10/2008 7:44:00 AM
Ramesh wrote:
> Hi,
>
> I need to convert unsigned long data to a std::string, I googled a bit
> to see if the string class supports any methods to achieve this - but
> didnt find any, I think of using sprintf and converting to a char buf
> and then putting it back in std::string -
>
> is anyone aware of any other way?
If you are used to sprintf but want something that deals with std::string
instead, you could try this:
bool strprintf ( std::string & buffer, char const * format, ... ) {
while ( true ) {
buffer.resize( buffer.capacity() );
int old_length = buffer.size();
std::va_list aq;
va_start( aq, format );
int length_needed =
vsnprintf( &buffer[0], old_length + 1, format, aq );
va_end( aq );
if ( length_needed < 0 ) {
return ( false );
}
buffer.resize( length_needed );
if ( length_needed <= old_length ) {
return ( true );
}
}
}
WARNING: the above is not standard compliant; it assumes that std::string is
contiguous (as far as I know, all implementations are, and it will be
required by the next iteration of the standard C++0X); also it requires
that is is legal to write a trailing 0 behind the string. Also, it assumes
that vsnprintf() conforms to C99 or C++0X. Thus, you have to test this
carefully.
Best
Kai-Uwe Bux