The C++ std::string::stof() function is used to convert a string to a floating point number. This function analyse the string, extracting a floating point value starting from the beginning of the string. If the conversion is successful, it returns the float value, otherwise it throws an invalid_argument exception.
SyntaxFollowing is the syntax for std::string::stof() function.
float stof (const string& str, size_t* idx = 0); float stof (const wstring& str, size_t* idx = 0);Parameters
This function has two parameters as described below.
This function returns the float value corresponding to the contents of the string passed as the argument.
Example 1Following is the basic example to convert a string into float of std::stof() function using C++.
#include <string> #include <iostream> using namespace std; int main() { string temperature = " 36.6"; float bodyTemp = stof(temperature); cout << "Body temperature is " << bodyTemp << " degree Celsius" << endl; return 0; }Output
If we run the above code it will generate the following output.
Body temperature is 36.6 degree CelsiusExample 2
Following is an another example passing a substring that contains a valid floating-point number, skipping the initial text.
#include <string> #include <iostream> using namespace std; int main() { string mixedContent = "Height: 180cm"; size_t pos; float height = stof(mixedContent.substr(7), & pos); cout << "Height = " << height << " cm " << endl; return 0; }Output
If we run the above code it will generate the following output.
Height = 180 cmExample 3
In this example we are converting multiple numbers from a single string using string::stof in C++.
#include <string> #include <iostream> #include <vector> using namespace std; int main() { string data = "3.14 1.618 2.718"; vector < float > numbers; size_t pos = 0, prev_pos = 0; while ((pos = data.find(' ', prev_pos)) != string::npos) { numbers.push_back(std::stof(data.substr(prev_pos, pos - prev_pos), nullptr)); prev_pos = pos + 1; } numbers.push_back(stof(data.substr(prev_pos), nullptr)); for (float num: numbers) { cout << num << std::endl; } return 0; }Output
Following is the output of the above code.
3.14 1.618 2.718Example 4
In this example we have given a invalid input, so it will throw an invalid_argument exception because the string cannot be converted to a float.
#include <string> #include <iostream> using namespace std; int main() { string invalidNumber = "abc123"; try { float value = stof(invalidNumber); cout << "Value is: " << value << std::endl; } catch (const invalid_argument & e) { cout << "Invalid argument: " << e.what() << endl; } return 0; }Output
Following is the output of the above code.
Invalid argument: stof
string.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4