Best way to cast numbers into strings in C++?
c++, c++11, casting, numbers, string
Solution
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`
Problem
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?