gpt4 book ai didi

c - 在 C 中使用 strok 解析 NMEA 字符串

转载 作者:行者123 更新时间:2023-11-30 18:47:30 27 4
gpt4 key购买 nike

我正在尝试使用带有分隔符 "," 的 strtok 函数解析 GNRMC 字符串,当我注意到一些我没有预料到的不同内容时,一切都很顺利。如果字符串包含连续的 ",," 那么 strtok 过冲和打印函数会放错真实数据,我的目标是当连续 < 之间没有可用数据时打印数字 0强>",,"

我该怎么做?

这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
char str[] = "$GPRMC,105954.000,A,3150.6731,N,11711.9399,E,0.00,96.10,250313,,,A*53";
char* Message_ID = strtok(str,",");
char* Time = strtok(NULL,",");
char* Data_Valid = strtok(NULL,",");
char* Raw_Latitude = strtok(NULL,",");
char* N_S = strtok(NULL,",");
char* Raw_Longitude = strtok(NULL,",");
char* E_W = strtok(NULL,",");
char* Speed = strtok(NULL,",");
char* COG = strtok(NULL,",");
char* Date = strtok(NULL,",");
char* Magnetic_Variation = strtok(NULL,",");
char* M_E_W = strtok(NULL,",");
char* Positioning_Mode = strtok(NULL,",");

double Latitude = atof(Raw_Latitude);
double Longitude = atof(Raw_Longitude);

printf("The Message ID is : %s\n", Message_ID);
printf("The Time is : %s\n", Time);
printf("The data valid is : %s\n", Data_Valid);
printf("The Latitude is : %f\n", Latitude);
printf("The N_S is : %s\n", N_S);
printf("The Longitude is : %f\n", Longitude);
printf("The E_W is : %s\n", E_W);
printf("The Speed is : %s\n", Speed);
printf("The COG is : %s\n", COG);
printf("The Date is : %s\n", Date);
printf("The Magnetic_Variation is : %s\n", Magnetic_Variation);
printf("The M_E_W is : %s\n", M_E_W);
printf("The Positioning_Mode is : %s\n", Positioning_Mode);

return 0;
}

输出窗口 Output Window

最佳答案

如果您只检测到一个特定字符(例如','),则直接的方法将使用古老的strchr().

 char str[] = 
"$GPRMC,105954.000,A,3150.6731,N,11711.9399,E,0.00,96.10,250313,,,A*53";

char* message_id = str;

char* time = strchr(message_id, ','); *time = '\0'; ++time;
char* data_valid = strchr(time,","); *data_valid = '\0'; ++data_valid;
char* raw_latitude = strchr(data_valid,","); *raw_latitude = '\0'; ++raw_latitude;
...

一个棘手的宏可以简化使用:

#define FIND_AND_NUL(s, p, c) ( \
(p) = strchr(s, c), \
*(p) = '\0', \
++(p), \
(p))

像这样使用它:

 char str[] = 
"$GPRMC,105954.000,A,3150.6731,N,11711.9399,E,0.00,96.10,250313,,,A*53";

char* message_id = str;

char* time = FIND_AND_NUL(message_id, time, ',');
char* data_valid = FIND_AND_NUL(time, data_valid, ',');
char* raw_latitude = FIND_AND_NUL(data_valid, raw_latitude, ',');
...

关于c - 在 C 中使用 strok 解析 NMEA 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48486952/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com