You can use sprintf
to convert each number to a string (and strcat
to place them one after the other if necessary). You should keep track of the length of the string to ensure you don't overflow it.
For example:
int var = 10;
char buf[20];
sprintf(buf, "%d", var); // buf string now holds the text 10
You don't need to make it much more complicated than this if you have a set format and amount of numbers. So if you always need one space between four numbers, you could do it all with one sprintf
and a format string like "%d %d %d %d"
(though this would require a much larger character array).
It'd be easy to write a small utility function that adds to an existing string, something like:
int add_to_string(char *buf, size_t sz, int num)
{
char tmp[20];
sprintf(tmp, " %d", num);
size_t len = strlen(tmp) + strlen(buf) + 1;
if (len > sz)
return -1;
strcat(buf, tmp);
return 0;
}
which you'd call with something like:
char buf[100];
sprintf(buf, "%d", 42);
add_to_string(buf, sizeof(buf), 9);
add_to_string(buf, sizeof(buf), 15);
add_to_string(buf, sizeof(buf), 8492);
add_to_string(buf, sizeof(buf), 35);
printf("String is '%s'\n", buf);
Output:
String is '42 9 15 8492 35'