Convert a string to an number is a quite common task in C++. This post summarizes the most common techniques to accomplish this task.
String to integer conversion
The first method is to construct an input stringstream initialized with the string to be converted and then reading the value into a variable using the » operator.
A second method is to use one of the following functions introduced in
- stoi, stol, stoll that converts from a string to an integer;
- stof, stod, stold that converts from a string to a floating-point value.
A third method is to use the C library function sscanf as in the following example converting a string to an integer:
Using “%f” in place of “%d” allows to convert a string to a floating-point value.
Integer to string conversion
The first method is to write the number to be converted into an output stringstream using the « operator and then getting the string using the str() member function.
It worth to observe that stringstreams manipulators can be used to customize the format of the resulting string. For example
set bla bla.
A second method is to use the function std::to_string() introduced in
This function is overloaded with different integer and floating-point types so that it can safely convert to string every number.
A third method is to use the C library function sprintf as in the following example converting an integer to a string:
Using “%f” in place of “%d” allows to convert a floating-point value into a string.
Comments