Locale-independent “atof”?

后端 未结 8 1848
余生分开走
余生分开走 2020-12-14 17:21

I\'m parsing GPS status entries in fixed NMEA sentences, where fraction part of geographical minutes comes always after period. However, on systems where locale defines comm

8条回答
  •  不知归路
    2020-12-14 18:18

    This question is old, but in the meantime in C++ we got a "locale-independent" atof:

    std::from_chars (with its sibling std::to_chars), added in c++17, provide locale-independent float scanning (and formatting). They are located in header .

    You can read more about them here:

    https://en.cppreference.com/w/cpp/utility/from_chars

    https://en.cppreference.com/w/cpp/utility/to_chars

    I recomment Stephan T. Lavavej wonderful talk about these two tools, here's the link to the part where he talks about using std::from_chars: https://youtu.be/4P_kbF0EbZM?t=1367

    And a short example by me:

    #include 
    #include 
    #include 
    
    int main()
    {
        char buffer[16] { "123.45678" };
        float result;
        auto [p, ec] = std::from_chars(std::begin(buffer), std::end(buffer), result);
        if(ec == std::errc{})
            std::cout << result;
    }
    

    Unfortunately, as for today (05.06.2020) only MSVC supports these functions with floating types. Implementing them efficiently turned out to be a big problem.

提交回复
热议问题