C++: Converting Strings and Numbers
×
Note: For examples of converting
QString objects to standard
strings and numbers in Qt,
follow this link.
This page provides several examples of how to convert
standard C++ string objects to numeric types, and
vice versa. The examples include older functions inherited from
C, as well as newer conversion functions introduced in C++11.
-
C++11: convert a
std::stringto anint:std::string someString = “55”;
int myInt = stoi(someString); -
C++11: convert a
std::stringto adouble:std::string someString = “98.6”;
double bodyTemp = stod(someString); -
C++11: convert a
std::stringto afloat:std::string someString = “105.9”;
float theX = stof(someString); -
C++11: convert a number to a
std::string:std::string myString = to_string(2345.89);
-
Convert a
std::stringto anint:std::string someStr = “180”;
int myInt = atoi(someStr.c_str()); // c_str() needed to convert C++ string to a C-string -
Convert a
std::stringto afloat:std::string someStr = “789.34”;
float myFloat = atof(someStr.c_str()); // c_str() needed to convert C++ string to a C-string