I am trying to concatenate an integer to a known string, and I have found that there are several ways to do it, two of those being:
int num=13;
string str = "Text" + static_cast<ostringstream*>( &(ostringstream() << num) )->str();
or I could also use boost
libraries' lexical_cast
:
int num=13;
string str= "Text" + boost::lexical_cast<std::string>(num);
Is the use of boost::lexical_cast
more efficient in any way, since I already know the conversion type (int
to string
)? Or is static_cast
just as effective, without having to rely on external libraries?
string str = "Text" + static_cast<ostringstream*>( &(ostringstream() << num) )->str();
This is ugly and not easily readable. Adding to this the fact that lexical_cast does almost exactly this underneath we can definitely say that using lexical_cast is "better".
In C++11, however, we have to_string
overloads.
string str = "Text" + to_string(num);
Which is the best option provided your compiler supports it.
See also How to convert a number to string and vice versa in C++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With