c - ANSI C : snprintf allocating issue

标签 c printf

我在使用 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/

相关文章:

bash - 为什么 printf (Unix) 使用 round half down?

c - 如何将小数打印成 32 位二进制,将其分隔 8 位

c - 编写自己的 printf 函数,尝试包含 %p。

c - 如何检查 fscanf() 在 C 中返回有效字符串?

c - 多线程自旋锁?

c - 修剪 C 中字符串的前导和尾随空格

c++ - fprintf 不写入管道

c - 如何在一行中打印指定数量的字符

c++ - Printf 不弹出

C - 指向结构组件(指针类型)的指针重新分配已中止(核心转储)