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
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 <charconv>
.
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 <charconv>
#include <iostream>
#include <system_error>
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.
I believe the simplest answer to this specific question would be to use the version of atof()
which takes a C locale parameter:
_locale_t plocale = _create_locale( LC_ALL, "C" );
double result = _atof_l( "01000.3897", plocale );
_free_locale( plocale );
This allows you to not mess with streams, or the global locale, or with manipulating the string, at all. Just create the desired locale object to do all your processing with and then free it when you are finished.