在c语言中char的固定格式,C语言简单处理报文中固定格式、固定分隔符的字符串...

自助设备给系统返回应答报文,其中最后一个域是TAG格式的字符串,包含多条数据记录,每条记录格式规定如下:

券别|钞箱金额|回收箱金额|合计金额|

其中金额均为16位,小数点后2位。

记录与记录之间有一个分隔符'\n',在linux系统下ASCII码是0X0A,例如:

"纸币100元|500.00|0.00|500.00|\n纸币50元|500.00|0.00|500.00|\n纸币20元|500.00|0.00|500.00|\n"

由于要对字符串里的数据进行处理,所以现在写函数提取字符串中的数据。

#include

#include

#include

typedef struct dataFormat{

char curType[15];

double boxAmt;

double cycAmt;

double totalAmt;

} *pDataFormat, DataFormat;

int main(int argc, char *argv[])

{

int i = 0;

char *p = NULL, *q = NULL;

char* teststr="纸币100元|500.00|0.00|500.00|\n纸币50元|500.00|0.00|500.00|\n纸币20元|500.00|0.00|500.00|\n";

char *tmpstr = NULL;

char tmp_box[17];

char tmp_cyc[17];

char tmp_total[17];

DataFormat rcvdata[10];

memset(tmp_box, 0x00, sizeof(tmp_box));

memset(tmp_cyc, 0x00, sizeof(tmp_cyc));

memset(tmp_total, 0x00, sizeof(tmp_total));

memset(rcvdata, 0x00, sizeof(DataFormat)*10);

p = teststr;

while(1)

{

q = strstr(p,"\n");

if(q != NULL)

{

printf("length:q-p=%d\n", q-p);

tmpstr = malloc(q-p+1);

strncpy(tmpstr, p, (q-p));

*(tmpstr+strlen(tmpstr)) = '\0';

printf(tmpstr);

printf("\n");

sscanf(tmpstr, "%[^|]|%[^|]|%[^|]|%[^|]|",rcvdata[i].curType, tmp_box, tmp_cyc, tmp_total);

// strtrim(rcvdata[i].curType);

rcvdata[i].boxAmt = atof(tmp_box);

rcvdata[i].cycAmt = atof(tmp_cyc);

rcvdata[i].totalAmt = atof(tmp_total);

printf("%s,%.2f,%.2f,%.2f\n", rcvdata[i].curType, rcvdata[i].boxAmt, rcvdata[i].cycAmt, rcvdata[i].totalAmt);

p = q+1;

i++;

}

else

{

break;

}

}

return 0;

}

编译运行:

gcc -o teststr teststr.c

./teststr

最终运行结果如下:

dce18577cb496c748baebf083c6ff97a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值