在字符数组 (C++/根) 中查找双精度值
Locating doubles in a char array (C++/ROOT)
我已经解析了一些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;
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 在字符数组 (C++/根) 中查找双精度值
- 查找大于双精度值的最小浮点数
- 如何查找输入的双精度是否为0.05的倍数
- 查找双精度数组中的第一个数字
- C++函数在一个双精度数组中查找最大值
- 向量<double>在容差水平内查找双精度
- 从文件输入中查找双精度数组的平均值