Say I have an array of longs, and some of the terminating elements might be NULL.
long array[30] = [172648712, 27146721, 27647212, NULL, NULL]
and I want to convert this array to an ASCII string separated by \n.
I want
char bufOut[MAXLINE] = "172648712\n27146721\n27647212"
How would I go about doing this in C? Of course in Python it would just be "\n".join(array)
but life isn't that easy down this low.
CodePudding user response:
A longer, but perhaps more clear version. Explanations are in the comments
#include<stdio.h>
#include<string.h>
#define MAXLINE 512
int main(void)
{
// correctly define array with brackets, end with 0 terminator
long array[30] = {172648712, 27146721, 27647212, 0};
// create a string MAXLINE long, initialized to '\0'
char buf[MAXLINE] = { 0 };
// initialize its string length to 0
size_t strLen = strlen(buf);
// loop until array contains a 0 value. If it does not contain a zero, this could
// search beyond the array bounds invoking UB
for (int i=0; array[i] != 0; i )
{
// plenty of space for a long
char temp[32];
// write the array value to a temp string with a trailing newline, checking how many
// bytes were written
strLen = sprintf(temp, "%ld\n", array[i]);
// checking -1 because sprintf return does not include the NUL terminator
if (strLen < sizeof(buf) - 1)
{
// append temp to buf
strcat(buf, temp);
}
else
{
// our string is out of space, handle this error how you want. If buf
// was dynamically allocated, here you could realloc and continue on
fprintf(stderr, "Source string out of space");
break;
}
}
printf("%s", buf);
return 0;
}
CodePudding user response:
char *convert(char *buff, const long *array, const long sentinel, size_t size)
{
char *wrk = buff;
while(size-- && *array != sentinel)
{
wrk = sprintf(wrk, "%ld%s", *array, (size && array[1] != sentinel) ? "\n" : "");
array ;
}
return buff;
}