STOF()

This function converts a string into a floating-point number of type float. It takes a std::string (or C-style string) as input and returns its floating-point representation. The function also allows an optional second argument to specify the starting position for conversion and to output the index of the first character not used in the conversion. If the input string does not contain a valid float or if the value is out of the range representable by a float, stof() throws exceptions like std::invalid_argument or std::out_of_range. This function is commonly used for parsing floating-point values from text, such as when reading data from files or user input.

//SYNTAX
float decimal = stof(stringValue); // Convert string to float
#include <iostream>     // For input and output
using namespace std;

int main() {
    string intString = "42";      // String representing an integer
    string floatString = "3.14";  // String representing a float

    int number = stoi(intString);     // Convert to int
    float decimal = stof(floatString); // Convert to float

    cout << "Integer: " << number << endl;
    cout << "Float: " << decimal << endl;

    return 0;  // End of program
}

 OUTPUT:
  Integer: 42  
  Float: 3.14

Last updated