This post will discuss how to convert a string to a float in C++.

1. Using std::stof

Starting with C++11, we can use the std::stof function to parse a string as a floating-point number. Here is a simple, short, and elegant C++11 solution demonstrating this:

Download  Run Code

 
To get the returned value of type double, use the std::stod function instead:

Download  Run Code

 
A better option is to use the strtof() and strtod() functions, to get a floating-point number as a float or double, respectively. This function is fail-safe and never throws exceptions.

Download  Run Code

2. Using sscanf() function

The sscanf() function can be used to read the formatted data from a string. The string is converted to the corresponding data type, as per the format specifier. To get a float value, use the %f format specifier. Similarly, use the %lf format specifier to get a double value.

Download  Run Code

3. Using std::istream::operator>>

The std::istringstream class is an input stream class to operate on strings. We can call the extraction operator (>>) to extract and parse characters from the input stream to the desired type value. This is demonstrated below:

Download  Run Code

4. Using Boost

Alternatively, we can use the boost’s lexical_cast library for converting a string to float or double in C++. It internally uses streams.

Download Code

5. Using std::from_chars

Since C++17, we can use std::from_chars function, defined in header <charconv>. The following code example shows invocation for this function:

Download Code

 
The std::from_chars function does not throw any exception. However, we can use the enumeration std::errc defined in header <system_error> to check for any errors.

Download  Run Code

That’s all about converting a string to a float in C++.