用c ++ / c解析nmea csv用于微芯片

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

如何解析逗号分隔的char字符串?我尝试过使用strtok,但我无法使用它。

     char str2[] = "$GNRMC,011802.00,A,4104.22420,N,08131.66173,W,0.021,,280218,,,D*78\n";


     char *p;

     p = strtok(str2, ",");




       char *input[8];
        int i = 0;
for( i=0;i<8;i++)
   {
    input[i] = p;
    p = strtok(NULL, ",");  

   }

理想情况下,我希望能够将变量设置为字符串。如

if (i == 0){
string type = $GNRMC;
}

if (i == 1){
float thisnum = 011802.00
}

等等

这是为pic写的,所以我不能使用矢量。

c csv pic microchip nmea
1个回答
0
投票

除了两个小问题之外,你的上层代码片段对我有用:

  • buf应该是str2
  • 你的char指针数组太小,无法容纳所有子串

对于第二个,您需要首先将子字符串转换为正确的类型。

__

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

int main(){

#define NUM_SUBSTRINGS 13

char str2[] = "$GNRMC,011802.00,A,4104.22420,N,08131.66173,W,0.021,,280218,,,D*78\n";
char *p;
p = strtok(str2, ",");

char * input[NUM_SUBSTRINGS];
int i = 0;

for(i=0; i<NUM_SUBSTRINGS; i++)
{   
    char *type = NULL;
    float thisnum = 0.0;
    if (i == 0){
        type = p;
    }

    if (i == 1){
        thisnum = strtof(p, NULL);
    }

    if(p != NULL)
        printf("String %s, type: %s, num: %f\n", p, type, thisnum);

    input[i] = p;
    p = strtok(NULL, ",");  

}
return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.