views:

61

answers:

5

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].

+2  A: 

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]);
}
codaddict
yeah, i'll try snprintf. thanks :D.. sometimes the first idea is the best one. damn it :)
mkind
A: 

use this:

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

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;
}
Brian R. Bondy
A: 

i solved it using snsprintf

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

thanks for your answers!!

mkind
A: 

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

thatsalok