std::ostringstream

B

bob

For reasons that are irrelevant , we cannot use sprintf to do
conversions between doubles, ints etc. to char*. We're using the
std::eek:stringstream type. Basically we have a function that takes a
double and needs to store a string representation of it into a vector
of strings. ...
something like this;

void pussy::(const double d)
{
std::eek:stringstream strm;
strm << d;

stringbuf *pbuf = strm.rdbuf();
_vect[some_index] = pbuf->str();

}

however this code involves taking a copy of the contents of pbuf string
and I'd like to avoid that. Is there a more efficient way of achieving
my goal without using sprintf etc.
thanks

G
 
D

Daniel T.

For reasons that are irrelevant , we cannot use sprintf to do
conversions between doubles, ints etc. to char*. We're using the
std::eek:stringstream type. Basically we have a function that takes a
double and needs to store a string representation of it into a vector
of strings. ...
something like this;

void pussy::(const double d)
{
std::eek:stringstream strm;
strm << d;

stringbuf *pbuf = strm.rdbuf();
_vect[some_index] = pbuf->str();

}

however this code involves taking a copy of the contents of pbuf string
and I'd like to avoid that. Is there a more efficient way of achieving
my goal without using sprintf etc.
thanks

Have you looked into boost.org "lexical_cast"? I personally feel that it
is the best (it even looks like a standard C++ cast.)

string s = lexical_cast<string>( myDouble );

Below is a naive implementation of it, I expect that Boost's full
implementation is faster.

template < typename Result, Input >
Result lexical_cast( Input in ) {
stringstream ss;
Result result;
if ( !( ss << in && ss >> result ) ) throw std::bad_cast();
return result;
}
 
B

bob

Genius! I've been looking for a reason to use boost for a while
now....this is ideal. :)

cheers mate,

G
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top