std::stof in C++

2

Parses string interpreting its content as a floating-point number, which is returned as a value of type float.

Syntax :

float stof (const string&  str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);

Parameters :
str : String object with the representation of a floating-point number.
idx : Pointer to an object of type size_t, whose value is set by the function
to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.

Return Value :
On success, the function returns the converted floating-point number as a value of type float.

Below is the C++ implementation of std::stof :

// CPP code to convert floating 
// type number to string
#include <bits/stdc++.h>

int main()
{
    // String to be parsed
    std::string str = "100.80";

    // val to store parsed floating type number
    float val = std::stof(str);

    // Printing parsed floating type number
    std::cout << val;

    return 0;
}

Output:

100.8
// CPP code to convert integer 
// type number to string
#include <bits/stdc++.h>

int main()
{
    // String to be parsed
    std::string str = "1000";

    // val to store parsed integer type number
    float val = std::stof(str);

    // Printing parsed integer type number
    std::cout << val;

    return 0;
}

Output:

1000

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.