What is the easiest way to convert from int
to equivalent string
in C++. I am aware of two methods. Is there any easier way?
(1)
Using stringstream for number conversion is dangerous!
See http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ where it tells that operator<<
inserts formatted output.
Depending on your current locale an integer greater than 3 digits, could convert to a string of 4 digits, adding an extra thousands separator.
E.g., int = 1000
could be convertet to a string 1.001
. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string
way. It is easier and does what you expect.
Updated (see comments below):
C++17 provides
std::to_chars
as a higher-performance locale-independent alternative