通过sscanf处理GPS信息

C语言提供了scanf通过IO格式化输入字符串,同样也提供了sscanf可以处理字符串,用于提取字符串中的有用信息。

之前在处理字符串的时候都是一个个字符遍历,如果要取中间的数值,还得把字符转为数字,然后做乘法加法,很是麻烦。

用sscanf可以将原来几十行的代码简化到一两行,见以下程序。

#include 
#include 
#include 

typedef	unsigned int			UINT32;
typedef	unsigned long long		UINT64;
typedef	UINT32					BOOL;
#define	TRUE					1
#define	FALSE					0

/* 日期时间结构体 8 bytes */
#pragma pack(1) 
typedef union _ZGDateTime
{
	UINT64 Ticks;

	struct  _tm
	{
		UINT32	US			: 12;	
		UINT32	MS			: 12;
		UINT32	Second		: 8;


		UINT32	Minute		: 6;
		UINT32	Hour		: 5;
		UINT32	Day			: 5;
		UINT32	Month		: 4;
		UINT32	Year		: 12;	
	}tm;
}ZGDateTime;

/* 定义GPS信息结构体 */
typedef struct _GPS_INFO_STRU
{
	ZGDateTime	dt;
	char		status;				// 状态A-有效,V为非有效接收警告,即当前天线视野上方的卫星个数少于3颗。
	float		latitude_value;		// 纬度值
	char		latitude;			// 纬度为N南纬或S北纬
	float 		longtitude_value;	// 经度值
    char 		longtitude;			// 经度标明东西半球,E为东半球、W为西半球
	float 		speed;				// 速度
    float 		azimuth_angle;		// 方位角
}GPS_INFO;


/*获取GPS信息,只处理$GPRMC*/
BOOL GetGpsInfo(const char *pStr, GPS_INFO *pGpsInfo)
{
	BOOL bl;
	int i;
	int year,month,day,hour,minute,second,ms;

	ZGDateTime	*dt;
	dt = &pGpsInfo->dt;


	
	memset(pGpsInfo, 0, sizeof(GPS_INFO));
	i = sscanf(pStr, "$GPRMC,%2d%2d%2d.%d\
			  %*[^VAva]%c,\
			  %f%*[^SNsn]%c,\
			  %f%*[^EWew]%c,\
			  %f,%f,\
			  %2d%2d%2d",  
			  &hour, &minute, &second, &ms,
			  &pGpsInfo->status, &pGpsInfo->latitude_value, &pGpsInfo->latitude,
			  &pGpsInfo->longtitude_value, &pGpsInfo->longtitude,
			  &pGpsInfo->speed, &pGpsInfo->azimuth_angle,
			  &day, &month, &year
			  );
	if(i >= 14 && (pGpsInfo->status == 'A' || pGpsInfo->status == 'a'))
	{
		dt->tm.Year = 2000+year;
		dt->tm.Month = month;
		dt->tm.Day = day;
		dt->tm.Hour = hour;
		dt->tm.Minute = minute;
		dt->tm.Second = second;
		dt->tm.MS = ms;
		dt->tm.US = 0;
		
		bl = TRUE;
	}
	else
	{
		bl = FALSE;
	}
	


	return bl;
}


int main()
{
	const char TestGpsText[]={"$GPRMC,024813.640,a,3158.4608,N,11848.3737,E,10.05,324.27,150706,,,A*50"};
	GPS_INFO	gpsInfo;
	GPS_INFO	*pGpsInfo;
	ZGDateTime	*dt;
	BOOL		bl;

	
	pGpsInfo = &gpsInfo;
	dt = &pGpsInfo->dt;
	bl = GetGpsInfo(TestGpsText, pGpsInfo);
	if(bl == TRUE)
	{
		printf( "%s %s\r\n", __DATE__, __TIME__);
		printf( "GPS信息:\r\n");
		printf( "时  间:%04d-%02d-%02d %02d:%02d:%02d %03d.%03d\r\n",
				   dt->tm.Year, dt->tm.Month, dt->tm.Day,
				   dt->tm.Hour, dt->tm.Minute, dt->tm.Second,
				   dt->tm.MS, dt->tm.US);
		printf( "状  态:%s\r\n", pGpsInfo->status == 'A' ? "有效" : "无效");
		printf( "经  度:%s%0.4f度\r\n", pGpsInfo->longtitude == 'E'? "东经" : "西经", pGpsInfo->longtitude_value);
		printf( "纬  度:%s%0.4f度\r\n", pGpsInfo->latitude == 'N'? "北纬" : "南纬", pGpsInfo->latitude_value);
		printf( "速  度:%.3f\r\n", pGpsInfo->speed);
		printf( "方位角:%.3f\r\n\r\n", pGpsInfo->azimuth_angle);
	}
	else
	{
		printf( "GPS数据无效\r\n");
	}
	system("pause");
}


你可能感兴趣的:(C)