Locale-independent “atof”?

后端 未结 8 1828
余生分开走
余生分开走 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:15

    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;
    }
    

提交回复
热议问题