开发者

fill a buffer successively

i intend to fill a char-pointer array successively in a for-loop. the content to fill in is a integer so i need to cast. but i didn't get the result i want to..

for (i=0;i<max0;i++){
    sprintf(buf, "%d", content[i]);
}

sprintf replaces 开发者_运维问答the hole buf, but i want to append.

for (i=0;i<max0;i++){
   buf[i]=(char) contint[i]
}

but this isn't working too. it seems to me, i get ascii-code of the content[i].


sprintf returns the number of char written. You can make use of this in appending the integers to the buffer.

Something like:

int pos = 0;
for (i=0;i<max0;i++){
   pos += sprintf(buf+pos, "%d", content[i]);
}


You can accomplish this using pointer arithmetic:

char *p = buf;
for (i=0;i<max;i++)
{
      int num_written = sprintf(p, "%d", content[i]);
      if(num_written == -1)
      { 
       //error handling 
       break;
      }

      p += num_written;
}


use this:

for (i=0; i<max0; ++i){
  sprintf(buf, "%d", content[i]);
  strcat(resultbuf, buf);
}


i solved it using snsprintf

for (i=0;i<max0;i++){
   length += snprintf(buf+length, buflen-length, "%d", content[i]);
}

thanks for your answers!!


I think it might sound silly, but i tweaked your code something like this:-

for (i=0;i<max0;i++){ 
   buf[i]=(char) (48+ contint[i]);
} 

// here 48 is ascii code of 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜