Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::string_view to float

Tags:

c++

I am trying to convert std::string_view to float without an intermediate conversion to std::string (which will cause extra heap allocation) with a C++20 compiler.

#include <iostream>
#include <charconv>

int main() {
    std::string_view s = "123.4";
    float x;
    std::from_chars(s.data(), s.data() + s.size(), x);
        
    std::cout << x << std::endl;
}

But I am unable to compile this code:

error: no matching function for call to 'from_chars(std::basic_string_view<char>::const_pointer, std::basic_string_view<char>::const_pointer, float&)'

What I am doing wrong?

like image 929
kiv_apple Avatar asked Oct 23 '25 00:10

kiv_apple


1 Answers

GCC's C++ standard library implementation first supported std::from_chars for float in GCC 11.1. 10.x won't support it.

Since you're not checking for success, and you know your string is null-terminated, you can use atof() instead, which is similarly unsafe. If you want proper checking for parsing errors, use strtof, which will give you similar information to from_chars as to whether the input matched properly:

#include <iostream>
#include <cstdlib>

int main() {
    std::string_view s = "123.4";
    char * end;
    float x = std::strtof(s.data(), &end);
    if (end != s.data() + s.size())
    {
        std::cout << "Parse error";
    }
    else
    {
        std::cout << x << std::endl;
    }
}
like image 138
Sneftel Avatar answered Oct 24 '25 13:10

Sneftel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!