我想对子字符串进行修改,并修改我的字符串(定义如下)。
char gps[]="$GPGGA,115726.562,4512.9580,N,03033.0412,E,1,09,0,9,300,M,0,M,,*6E";
不久,我想获取并增加纬度,经度数据,这意味着
我的脚步
将经纬度信息设为char或float
将lat(char)转换为float
将步长值添加到浮动
将lat(float)转换为char为newlat
将newlat插入gps []
打印
char substr[10]; //4512.9580 //#number of char
memcpy(substr,&gps[19],10); //memcpy from gps char start from 19 take 9 char character
substr[10]='\0'; //I dont know what makes it
char lat[10]=??? //I dont know how I will take lat data
float x; //defined float value
x=atof(lat); //convert string to float
x=x+0.1; //add step value to float (4513.0580)
char newlat[10]; //newlat defined
sprintf(newlat,x); //convert to float to string
???? //I dont know how I can put into gps[]
最佳答案
#include <stdio.h>
#include <string.h>
int add(char *x, const char *dx){
//Note that this is not a general-purpose
int ppos1 = strchr(x, '.') - x;
int ppos2 = strchr(dx, '.') - dx;
int len2 = strlen(dx);
//4512.9580
//+ 0.1
int i = len2 -1;//dx's last char
int j = ppos1 + (i-ppos2);//x's add position
int carry = 0;
for(;i>=0 || (j>=0 && carry);--i, --j){
if(dx[i]=='.')
continue;
int sum = (x[j]-'0')+(i>=0)*(dx[i]-'0')+carry;
x[j] = sum % 10 + '0';
carry = sum / 10;
}
return carry;
}
int main(){
char gps[]="$GPGGA,115726.562,4512.9580,N,03033.0412,E,1,09,0,9,300,M,0,M,,*6E $GPRMC,115726.750,A,4002.9675,N,03233.0412,E,173.8,0,071114,003.1,E*72"; int m,k,j,i,n;
char *field, *rest;
field = strchr(gps, ',');//1st ','
field = strchr(field+1, ',')+1;//2nd ',' next(+1) : 3rd field
rest = strchr(field, ',');//3rd ','
int substr_len = rest - field;
char substring[substr_len + 1];
memcpy(substring, field, substr_len);
substring[substr_len] = '\0';
if(add(substring, "0.1")){//Carry occurred
char newgps[sizeof(gps)+1];
*field = '\0';
strcpy(newgps, gps);
strcat(newgps, "1");
strcat(newgps, substring);
strcat(newgps, rest);
printf("%s\n", newgps);
} else {
memcpy(field, substring, substr_len);//rewrite
printf("%s\n", gps);
}
return 0;
}