假設我有一個 long 陣列,并且某些終止元素可能為 NULL。
long array[30] = [172648712, 27146721, 27647212, NULL, NULL]
我想將此陣列轉換為由 \n 分隔的 ASCII 字串。
我想要
char bufOut[MAXLINE] = "172648712\n27146721\n27647212"
我將如何在 C 中執行此操作?當然,在 Python 中它只是這樣,"\n".join(array)但在這么低的情況下,生活并不那么容易。
uj5u.com熱心網友回復:
一個更長但也許更清晰的版本。解釋在評論里
#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;
}
演示
uj5u.com熱心網友回復:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370115.html
上一篇:具有相同值的過濾器陣列
