0

I have multiple int variables , each int is about 4 to 6 digits.

I want to combine them into one big string (char *) and add symbol '>' in between each integers

which would be some thing like :

int  a = 123456, b = 2244, c = 23456, d = 54321;
char * str;

and out put string would be like this : 123456>2244>23456>54321\0

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
azgt
  • 37
  • 1
  • 6
  • 1
    possible duplicate of [C - casting int to char and append char to char](http://stackoverflow.com/questions/5008394/c-casting-int-to-char-and-append-char-to-char) – elias Feb 13 '15 at 02:28

2 Answers2

0

Try this

char string[100];
snprintf(string, sizeof(string), "%d>%d>%d>%d", a, b, c, d);

If you mean an array with variable length, you can do it this way

#include <stdio.h>
#include <string.h>

int main()
{
    int  array[5] = {1, 2, 3, 4, 5};
    char string[1024];
    int  size;

    size  = sizeof(string);
    size -= snprintf(string, sizeof(string), "%d", array[0]);
    for (size_t i = 1 ; ((i < sizeof(array) / sizeof(array[0])) && (size > 0)) ; ++i)
    {
        char current[100];

        snprintf(current, sizeof(current), ">%d", array[i]);

        size -= strlen(current);
        if (size >= 0)
            strcat(string, current);
    }   
    printf("%s\n", string);
    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • what about if all int variables are stored in a int array? – azgt Feb 13 '15 at 02:11
  • @azgt can you please elaborate, i fail to see any difference, it would just be `snprintf(string, sizeof(string), "%d>%d>%d>%d", array[0], array[1], array[2], array[3]);` – Iharob Al Asimi Feb 13 '15 at 02:14
  • Sorry I forgot to say that the length of array can only be determined in run-time – azgt Feb 13 '15 at 02:16
0

How about:

char buf[n*7+1]; /* big enough for 6 digits per, plus >. See my comment below. */
char * cur = buf; /* points to start of buf. */
int i;
for(i=0; i<n; ++i) {
  /* sprintf returns the number of characters converted, so
     this advances the pointer to the end of the added chars. */
  cur += sprintf(cur, "%d>", array[i]);
}
*(cur - 1) = '\0'; /* get rid of the last > */

I haven't compiled this, so you may have to make some mods.

Sniggerfardimungus
  • 11,583
  • 10
  • 52
  • 97
  • 1
    Isn't this undefined behavior? Also, you account for `6` digits and each `>` but not the terminating `'\0'`. – Iharob Al Asimi Feb 13 '15 at 02:27
  • The last \0 gets put where the last group's > was written. But you have a point, the last sprintf could write 1 beyond the end of the buffer, so the size of the buffer should be n*7+1. I don't know if the standard leaves the return value undefined, but I've never run into an implementation that doesn't. I just checked the man page for my linux machine, tried it under cygwin and OS X, and they all worked as I described. – Sniggerfardimungus Feb 13 '15 at 07:06