C++ std::stof() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::stof

Definition

In C++, std::stof() converts a string to float.

Include <string>.

This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::stof(...).

Syntax

Pass floating text.

C++
float f = std::stof("3.14");
CallWhat it does
std::stof(str)Parse as float; optional idx.

For double precision use stod; for long double use stold.

Library declarations
C++
float stof(const string& str, size_t* idx = 0);

Parameters

ParameterDescription
strInput.
idxOptional end index.

Return Value

Return ValueDescription
floatParsed value.

C++ Examples

Example 1 — Basic stof()

Convert a decimal string.

C++
#include <iostream>
#include <string>

int main() {
    float f = std::stof("3.5");
    std::cout << f << '\\n';
    return 0;
}

How It Works

  1. Text represents a decimal.
  2. stof yields a float.
  3. Printed approximately 3.5.

Example 2 — Scientific Text

Parse exponential notation.

C++
#include <iostream>
#include <string>

int main() {
    float f = std::stof("1e3");
    std::cout << f << '\\n';
    return 0;
}

How It Works

  1. 1e3 means 1×10³.
  2. stof understands it.
  3. Result is 1000.

Example 3 — stof idx

Stop after the number.

C++
#include <iostream>
#include <string>

int main() {
    std::size_t i = 0;
    float f = std::stof("2.5cm", &i);
    std::cout << f << ' ' << i << '\\n';
    return 0;
}

How It Works

  1. Parses 2.5.
  2. Stops before c.
  3. idx is 3.

Frequently Asked Questions

Parses a float from a string.
stod.
Yes on invalid/out of range.
<string>.
Uses the global C locale style parsing like strtof.

Next: stoi()

Keep going through the string functions. Convert a string to int.

stoi() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful