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
Any reason why you can't do a setlocale "C" before the atof and restore the locale afterwards? Maybe I misunderstood the question...
You could always use (modulo error-checking):
#include <sstream>
...
float longitude = 0.0f;
std::istringstream istr(pField);
istr >> longitude;
The standard iostreams use the global locale by default (which in turn should be initialized to the classic (US) locale). Thus the above should work in general unless someone previously has changed the global locale to something else, even if you're running on a non-english platform. To be absolutely sure that the desired locale is used, create a specific locale and "imbue" the stream with that locale before reading from it:
#include <sstream>
#include <locale>
...
float longitude = 0.0f;
std::istringstream istr(pField);
istr.imbue(std::locale("C"));
istr >> longitude;
As a side note, I've usually used regular expressions to validate NMEA fields, extract the different parts of the field as captures, and then convert the different parts using the above method. The portion before the decimal point in an NMEA longitude field actually is formatted as "DDDMM.mmm.." where DDD correspond to degrees, MM.mmm to minutes (but I guess you already knew that).
You could iterate through all the characters in the array and swap any non-numbers with a .
character, which should work as long as the coordinates are in a number-single_delimiter_character_-number
format.
Do you really need to get locale behavior for numerics? If not
setlocale(LC_ALL|~LC_NUMERIC, "");
or the equivalent use of std::locale constructor.
A nasty solution I've done once is to sprintf()
0.0f and grab the second character from the output. Then in the input string replace '.' by that character. This solves the comma case, but would also work if a locale defined other decimal separators.
Some of the solutions above did not seem to work, so I propose this as a perfectly failproof solution. Just copy-paste this function and use it instead.
float stor(const char* str) {
float result = 0;
float sign = *str == '-' ? str++, -1 : 1;
while (*str >= '0' && *str <= '9') {
result *= 10;
result += *str - '0';
str++;
}
if (*str == ',' || *str == '.') {
str++;
float multiplier = 0.1;
while (*str >= '0' && *str <= '9') {
result += (*str - '0') * multiplier;
multiplier /= 10;
str++;
}
}
result *= sign;
if (*str == 'e' || *str == 'E') {
str++;
float powerer = *str == '-'? str++, 0.1 : 10;
float power = 0;
while (*str >= '0' && *str <= '9') {
power *= 10;
power += *str - '0';
str++;
}
result *= pow(powerer, power);
}
return result;
}