我在使用 snprintf()
函数时遇到此问题。我想连接多个字符串。
我有一个结构msg
定义为
struct timerMessage {
char txncode[4];
char date[8];
char time[6];
char mac[16];
char userid[32];
char instid[9];
char merchcode[2];
char seqno[3];
char data[100];
} msg;
具有这些值:
{txncode = "9902", date = "08082015", time = "172936", mac = ' ' <repeats 16 times>,
userid = ' ' <repeats 32 times>, instid = " ", merchcode = " ", seqno = "001",
data = "FILE1TEST11|1P", '\000' <repeats 85 times>}
这就是我连接字符串的方式:
snprintf(msgbuffer,sizeof(msgbuffer),"%s%s%s%s%s%s%s%s%s",msg.txncode,
msg.date,msg.time,msg.mac,msg.userid,msg.instid,msg.merchcode,msg.seqno,msg.data);
更新:MCVE
结构消息
char txncode[4] ,date[8], time[6], mac[16], userid[32], instid[9], merchcode[2], seqno[3], data[100];
变量
sprintf(msg.txncode, "%s","9901");
sprintf(msg.date, "%002d%002d%002d",month,day,year);
sprintf(msg.time, "%002d%002d%002d",hr,min,sec);
sprintf(msg.mac, "% 16s", " ");
sprintf(msg.userid, "% 32s", " ");
sprintf(msg.instid, "% 9s", " ");
sprintf(msg.merchcode,"% 2s", " ");
sprintf(msg.seqno,"%003d",1);
snprintf(msg.data,sizeof(msg.data),"%s|%s","FILE1TEST11","1P");
连接的结果:
"990208082015172936", ' ' (repeats 59 times), "001FILE1TEST11|1P0808"
结果应该是:
"990208082015172936", ' ' (repeats 59 times), "001FILE1TEST11|1P"
最佳答案
您这里只有一个问题。在所有字符数组中,您将用值填充所有可用位置,并且任何位置都不能包含 NULL ('/0')
字符。通过在每个字符数组中添加一个字符来修改您的结构,如下所示,您将获得所需的结果。
3 struct timerMessage {
4 char txncode[5];
5 char date[9];
6 char time[7];
7 char mac[17];
8 char userid[33];
9 char instid[10];
10 char merchcode[3];
11 char seqno[4];
12 char data[100];
13 } msg;
关于c - ANSI C : snprintf allocating issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875004/