与区域无关的“atof”? [英] Locale-independent "atof"?

查看:238
本文介绍了与区域无关的“atof”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析固定NMEA句子中的GPS状态条目,其中地理分钟的小部分总是在句点之后。但是,在区域设置将逗号定义为小数分隔符的系统上, atof 函数忽略句点和整数部分。

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 comma as decimal separator, atof function ignores period and whole fraction part.

有这个问题?

示例代码

m_longitude = atof((char *)pField); 

其中

pField[] = "01000.3897"; 

跨平台项目,为Windows XP和CE编译。

Cross-platform project, compiled for Windows XP and CE.

评论解决方案:

接受的答案更加优雅,但这个答案(和评论)也值得一试,作为一个快速修复

Accepted answer is more elegant, but this answer (and comment) is also worth knowing as a quick fix

推荐答案

您可以随时使用(模错误检查):

You could always use (modulo error-checking):

#include <sstream>
...

float longitude = 0.0f;
std::istringstream istr(pField);

istr >> longitude;

标准iostreams默认使用全局区域设置)locale)。因此,以上应该一般工作,除非有人以前已经改变了全球区域设置为别的,即使你在非英语平台上运行。要绝对确保使用所需的语言区域,请创建特定语言区域,然后在阅读之前先使用该语言区域填充流程:

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;

注意,我通常使用正则表达式来验证NMEA字段,的字段作为捕获,然后使用上述方法转换不同的部分。在NMEA经度字段中的小数点之前的部分实际上被格式化为DDDMM.mmm ..,其中DDD对应于度,MM.mmm到分钟(但我猜你已经知道)。

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).

这篇关于与区域无关的“atof”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆