Question on converting unsigned long to std::string

R

Ramesh

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?

Thanks
/R
 
K

Kai-Uwe Bux

Ramesh said:
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
 
J

Juha Nieminen

Ramesh said:
is anyone aware of any other way?

I really can't understand why two people have already answered your
question with overly long and complicated answers, which are also
basically just wrong. Come on, people, keep answers simple and
concentrate on the *basics*.

What you want is this:

std::eek:stringstream os;
os << yourUnsignedValue;
std::string theValueAsString = os.str();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,823
Latest member
Nadia88

Latest Threads

Top