将 std::string_view 转换为 float

kiv*_*ple 4 c++

我正在尝试使用 C++20 编译器转换std::string_view为浮点数,而无需中间转换(这将导致额外的堆分配)。std::string

#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;
}
Run Code Online (Sandbox Code Playgroud)

但我无法编译这段代码

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

我做错了什么?

Sne*_*tel 5

GCC 的 C++ 标准库实现首先在GCC 11.1std::from_chars得到支持。10.x 不支持它。float

由于您没有检查是否成功,并且您知道您的字符串以 null 结尾,因此您可以使用atof()来代替,这同样不安全。如果您想要正确检查解析错误,请使用strtof,它将为您提供与from_chars输入是否正确匹配类似的信息:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)