最近有人要求我使用 c 从 DMEA 代码中确定某些内容的坐标。代码示例是:
$GPGGA,181908.00,3404.7041778,N,07044.3966270,W,4,13,1.00,495.144,M,29.200,M,0.10,0000*40.
我需要在每个逗号之后将其分成几部分。有人知道如何用 C 实现这一点吗?
最佳答案
如果你的记录格式是固定的,那么使用*scanf例程来读取记录会很方便。它还将进行必要的数字类型转换。这是您的字符串的示例:
#include <stdio.h>
#include <string.h>
typedef struct Rec {
char var [128];
float x1, x2, x3, x4, x5, x6, x7, x8;
int i1, i2, i3;
char c1, c2, c3, c4;
} Rec; // Rename fields to something meaningful
int read_rec(Rec *o, const char *s)
{
int n = sscanf(s,
"%[^,],%f,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c,%f,%d*%f",
&o->var, &o->x1, &o->x2, &o->c1, &o->x3, &o->c2, &o->i1, &o->i2, &o->x4,
&o->x5, &o->c3, &o->x6, &o->c4, &o->x7, &o->i3, &o->x8);
if (n != 16 /* num of fields */) {
printf ("Rec struct reading failed after %d field(s) read: %s\n",
n, s);
return 0;
}
return 1;
}
void print_rec(const Rec *r, FILE *of)
{
fprintf(of,
"%s,%f,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c,%f,%d*%f",
r->var, r->x1, r->x2, r->c1, r->x3, r->c2, r->i1, r->i2, r->x4,
r->x5, r->c3, r->x6, r->c4, r->x7, r->i3, r->x8);
}
int main() {
const char *desc = "$GPGGA,181908.00,3404.7041778,N,07044.3966270,W,4,13,1.00,495.144,M,29.200,M,0.10,0000*40.";
struct Rec rec;
if (read_rec(&rec, desc))
print_rec(&rec, stdout);
return 0;
}
关于c - 如何在特定字符后剪切字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528192/