在字符数组 (C++/根) 中查找双精度值

Locating doubles in a char array (C++/ROOT)

本文关键字:查找 双精度 字符 数组 C++      更新时间:2023-10-16

我已经解析了一些XML数据,我想要纬度和经度信息。我需要解析的行是这样的:

trkptlat="60.397015"lon="5.32299"

这是 char 数组中的一个元素,如何将数字提取/解析为双精度?请注意,数字精度会随着数据的进行而变化,因此我不能仅仅依靠挑选列索引。

您使用 C 样式字符数组作为字符串。所以,我的假设你仍然在C.否则,你会std::string.Ìn C++没有使用 char 数组而不是std::string的 jsutization 。

请参阅C-Style解决方案:

#include <cstring>
#include <cstdlib>
#include <cstdio>
int main() {
char data[] = "SomeTrashMoreTrashtrkptlat="60.397015"lon="5.32299"MoreTrashMoreTrash";
char firstDoubleIndicator[] = "trkptlat="";
char secondDoubleIndicator[] = ""lon="";
double latitude = 0;
double longitude = 0;
char* startPosition = strstr(data, firstDoubleIndicator);
if (startPosition) {
latitude = std::atof(startPosition + std::strlen(firstDoubleIndicator));
}
startPosition = strstr(data, secondDoubleIndicator);
if (startPosition) {
longitude = std::atof(startPosition + std::strlen(secondDoubleIndicator));
}
std::printf("nlatitude:t%fnlongitude:t%fnn", latitude, longitude);
return 0;
}

这可以通过多种方式完成,警告完全未经测试的代码

使用安全版本的 sscan 及其如下所示的参数

""trkptlat="%d"lon="%d""

请务必检查返回值的长度和错误。

使用 std::find_first_of 与数字和点

auto start = find_first_of (haystack.begin(), haystack.end(), digits.begin(), digit.end());
auto end = find_first_of (it, haystack.end(), digitsdot.begin(), digitdot.end(), 
[](char a, char b){ return a != b; });
double lat = atof(start); // somewhere there might be a version that returns how many chars read also.
// check for errors
etc.

查看更多 http://www.cplusplus.com/reference/algorithm/find_first_of/

如果你是信任的人,你可以采取一些你知道的捷径

"trkptlat="

将作为前缀,以便您可以从

auto start = haystack+preLen;