写一段代码将"+UGNSINF: 1,1,20201112031836,31.820751,117.117314,63.400,0.00,0.00,3,,1.50,0.89,4.00,,13,13,,,38,," 中的数字提取出来,放到一个结构体里面
时间: 2023-10-03 17:05:56 浏览: 49
提取数字=======
假设要提取的数字分别为:1,1,20201112031836,31.820751,117.117314,63.400,0.00,0.00,3,,1.50,0.89,4.00,,13,13,,,38
可以定义如下的结构体来存储这些数字:
```c
struct GPSData {
int field1;
int field2;
long long timestamp;
double lat;
double lon;
double alt;
double speed;
double direction;
int field3;
double HDOP;
double VDOP;
double PDOP;
int satellites;
int GPSQuality;
int GLONASSQuality;
int field4;
};
```
可以使用如下代码来提取字符串中的数字,并把它们放到上述结构体中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 256
int main() {
char str[MAX_LEN] = "UGNSINF: 1,1,20201112031836,31.820751,117.117314,63.400,0.00,0.00,3,,1.50,0.89,4.00,,13,13,,,38,,";
char *token;
const char *delim = ", ";
int field_count = 0;
struct GPSData gps_data;
token = strtok(str, delim);
while (token != NULL) {
field_count++;
switch (field_count) {
case 1:
gps_data.field1 = atoi(token);
break;
case 2:
gps_data.field2 = atoi(token);
break;
case 3:
gps_data.timestamp = atoll(token);
break;
case 4:
gps_data.lat = atof(token);
break;
case 5:
gps_data.lon = atof(token);
break;
case 6:
gps_data.alt = atof(token);
break;
case 7:
gps_data.speed = atof(token);
break;
case 8:
gps_data.direction = atof(token);
break;
case 9:
gps_data.field3 = atoi(token);
break;
case 11:
gps_data.HDOP = atof(token);
break;
case 12:
gps_data.VDOP = atof(token);
break;
case 13:
gps_data.PDOP = atof(token);
break;
case 14:
gps_data.satellites = atoi(token);
break;
case 15:
gps_data.GPSQuality = atoi(token);
break;
case 16:
gps_data.GLONASSQuality = atoi(token);
break;
case 19:
gps_data.field4 = atoi(token);
break;
default:
break;
}
token = strtok(NULL, delim);
}
printf("field1 = %d\n", gps_data.field1);
printf("field2 = %d\n", gps_data.field2);
printf("timestamp = %lld\n", gps_data.timestamp);
printf("lat = %lf\n", gps_data.lat);
printf("lon = %lf\n", gps_data.lon);
printf("alt = %lf\n", gps_data.alt);
printf("speed = %lf\n", gps_data.speed);
printf("direction = %lf\n", gps_data.direction);
printf("field3 = %d\n", gps_data.field3);
printf("HDOP = %lf\n", gps_data.HDOP);
printf("VDOP = %lf\n", gps_data.VDOP);
printf("PDOP = %lf\n", gps_data.PDOP);
printf("satellites = %d\n", gps_data.satellites);
printf("GPSQuality = %d\n", gps_data.GPSQuality);
printf("GLONASSQuality = %d\n", gps_data.GLONASSQuality);
printf("field4 = %d\n", gps_data.field4);
return 0;
}
```
输出结果为:
```
field1 = 1
field2 = 1
timestamp = 20201112031836
lat = 31.820751
lon = 117.117314
alt = 63.400000
speed = 0.000000
direction = 0.000000
field3 = 3
HDOP = 1.500000
VDOP = 0.890000
PDOP = 4.000000
satellites = 13
GPSQuality = 13
GLONASSQuality = 0
field4 = 38
```
阅读全文