C-外部结构

问题描述 投票:1回答:2

我正在使用结构来处理NMEA消息,但是我不知道是什么,处理消息时出现了问题。所以,我有NMEA_parse.h:

/* GPRMC */
 #define TIME   2U
 #define LAT        4U
 #define LON        6U
 #define SPD        8U
 #define ANG        9U
 #define DATE   10U

extern struct gprmc{
    char time[10];
    char latitude[10];
    char longitude[10];
    char speed[10];
    char angle[10];
    char date[10];
}gprmc_datas;

NMEA_parse.c:

#include "NMEA_parse.h"

struct gprmc gprmc_datas;

static void fill_data (char* param_in)
{
    uint8_t i = 0U;             
    char* trunk;                
    char trunk_datas[20U][10U]; 

    trunk = strtok(param_in, ",");      
    while(trunk != NULL)
    {
        i++;        
        if(i > 20) { i = 0; }

        strcpy(trunk_datas[i],trunk);
        trunk = strtok (NULL, ",");     
    }

    if(memcmp(trunk_datas[1U],"GPRMC",6U) == 0U)
    {
        strcpy(gprmc_datas.time,trunk_datas[TIME]);
        strcpy(gprmc_datas.latitude,trunk_datas[LAT]);
        strcpy(gprmc_datas.longitude,trunk_datas[LON]);
        strcpy(gprmc_datas.date,trunk_datas[DATE]);
        strcpy(gprmc_datas.time,trunk_datas[TIME]);
    }
}

main.c:

#include <stdio.h>
#include "NMEA_parse.h"

int main(void)
{
    char *message = "$GPRMC,182127.00,A,4753.47678,N,02022.20259,E,0.837,,161019,,,A*7C\r\n";
    char *mes     = "$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A";
    proc_sentence(message);
    printf("\ntime: %s\n", gprmc_datas.time);
    printf("latitude: %s\n", gprmc_datas.latitude);
    printf("longitude: %s\n", gprmc_datas.longitude);
}

proc_sentence函数将消息传递给fill_data()(如果消息有效)(校验和等)当我使用mes作为输入时,一切都正确,但是当我切换到message时,会显示一些异常,因为结果如下:

时间: 182127.00

纬度: 4753.4767802022.2025E

经度: 02022.2025E

您知道发生了什么问题吗?

c++ c string struct extern
2个回答
0
投票

如果将结构中的纬度[10]更改为纬度[12],也可以使用字符串“ message”。


0
投票

与几乎所有其他有关scanf的使用的问题不同,您的问题实际上是为此而哭泣的问题。毕竟,如果机器编写了它,那么机器可以读取它,对吗?

使用C的字符串文字的串联,我非常接近用单个函数填充结构:

  int n = sscanf( message,
          "%[^,]," 
          "%[^,]," 
          "%*[^,],%[^,]," 
          "%*[^,],%[^,]," 
          "%*[^,],%[^,]," 
          "%[^,],"    
          "%[^,],", 
          label,
          gprmc.time, 
          gprmc.latitude, 
          gprmc.longitude, 
          gprmc.speed, 
          gprmc.angle, 
          gprmc.date );

这利用了很少使用的正则表达式说明符,我们在其中查找用逗号分隔的非逗号%[^]%*[^]指定跳过该字段。

© www.soinside.com 2019 - 2024. All rights reserved.