Coming from a C#
background, In C#
I could write this:
int int1 = 0;
double double1 = 0;
float float1 = 0;
string str = "words" + int1 + double1 + float1;
..and the casting to strings is implicit. In C++
I understand the casting has to be explicit, and I was wondering how the problem was usually tackled by a C++
programmer?
There's plenty of info on the net already I know, but there seems to quite a number of ways to do it and I was wondering if there wasn't a standard practice in place?
If you were to write that above code in C++
, how would you do it?
Strings in C++ are just containers of bytes, really, so we must rely on additional functionality to do this for us.
In the olden days of C++03, we'd typically use I/O streams' built-in lexical conversion facility (via formatted input):
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::stringstream ss;
ss << "words" << int1 << double1 << float1;
std::string str = ss.str();
You can use various I/O manipulators to fine-tune the result, much as you would in a sprintf
format string (which is still valid, and still seen in some C++ code).
There are other ways, that convert each argument on its own then rely on concatenating all the resulting strings. boost::lexical_cast
provides this, as does C++11's to_string
:
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ std::to_string(int1)
+ std::to_string(double1)
+ std::to_string(float1);
This latter approach doesn't give you any control over how the data is represented, though (demo).
std::stringstream
std::to_string
If you can use Boost.LexicalCast (available for C++98 even), then it's pretty straightforward:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main( int argc, char * argv[] )
{
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ boost::lexical_cast<std::string>(int1)
+ boost::lexical_cast<std::string>(double1)
+ boost::lexical_cast<std::string>(float1)
;
std::cout << str;
}
Live Example.
Note that as of C++11, you can also use std::to_string
as mentioned by @LigthnessRacesinOrbit.
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