使用C,干净利落将一个动态分配的int数组到一个逗号分隔的字符串越好 [英] Using C, convert a dynamically-allocated int array to a comma-separated string as cleanly as possible
问题描述
我用C少得多的经验比我更高层次的语言。在思科,我们使用C,我有时会碰到的东西,会很容易在Java或Python的事,但很难在C.现在要做的是这样的一个时期。
I’m much less experienced in C than I am in higher-level languages. At Cisco, we use C, and I sometimes run into something that would be easy to do in Java or Python, but very difficult to do in C. Now is one of those times.
我有我需要转换为是日志的逗号分隔的字符串无符号整数的一个动态分配的数组。虽然整数是不太可能是非常大的,他们可以在概念上是从0到4,294,967,295在Python中的任何地方,这是一短行。
I have a dynamically-allocated array of unsigned integers which I need to convert to a comma-separated string for logging. While the integers are not likely to be very large, they could conceptually be anywhere from 0 to 4,294,967,295 In Python, that’s one short line.
my_str = ','.join(my_list)
如何能优雅人们做这在C?我想出了一个办法,但它的毛。如果有人知道一个很好的办法做到这一点,请赐教。
How elegantly can people do this in C? I came up with a way, but it’s gross. If anyone knows a nice way to do it, please enlighten me.
推荐答案
与其他的答案,并不强制C99。
在这里真正的问题是不知道你会需要的字符串的长度。获得一个数字是为的sprintf一样简单(%U,* NUM)
使用 NUM
来走你的阵列 INT
S,但多少空间,你要需要什么?为了避免超越缓冲区,你必须追踪许多整数的。
The real problem here is not knowing the length of the string you're going to need. Getting a number is as easy as sprintf("%u", *num)
using num
to walk your array of int
s, but how much space are you going to need? To avoid overrunning a buffer, you have to keep track of a lot of integers.
size_t join_integers(const unsigned int *num, size_t num_len, char *buf, size_t buf_len) {
size_t i;
unsigned int written = 0;
for(i = 0; i < num_len; i++) {
written += snprintf(buf + written, buf_len - written, (i != 0 ? ", %u" : "%u"),
*(num + i));
if(written == buf_len)
break;
}
return written;
}
请注意,我跟踪多少缓冲的我已经使用并使用的snprintf
,所以我不超限结束。 的snprintf
将钉在一个 \\ 0
,但因为我使用 BUF +写
我将开始在 \\ 0
的previous 的snprintf
的
Notice, that I keep track of how much of the buffer I have used and use snprintf
so I don't overrun the end. snprintf
will tack on a \0
, but since I'm using buf + written
I will start at the \0
of the previous snprintf
.
在使用
int main() {
size_t foo;
char buf[512];
unsigned int numbers[] = { 10, 20, 30, 40, 1024 };
foo = join_integers(numbers, 5, buf, 512);
printf("returned %u\n", foo);
printf("numbers: %s\n", buf);
}
输出:
returned 20
numbers: 10, 20, 30, 40, 1024
强制限制踢,而不是超越:
Forcing the limiting to kick in, instead of overrunning:
char buf[15];
foo = join_integers(numbers, 5, buf, 14);
buf[14] = '\0';
输出,果然:
returned 14
numbers: 10, 20, 30, 4
这篇关于使用C,干净利落将一个动态分配的int数组到一个逗号分隔的字符串越好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!