2014-10-01 26 views
0

我会尝试在这里尽可能清楚,但基本上。 (我在c做这个) 我有一个数组(动态)的unsigned long long int,它是从while循环中增长的。 这些工作并不是什么奇特的东西,但我有一些getter函数可以根据问题提供信息。诠释数组中的字符串在c

即,获得前20个号码。这将返回一个长度为20个元素的无符号long long int数组。

因此用户将选择返回数组中的元素数量,因此它可能是1或它可能是20个大数字(即array [] =(1233,123444,1234124,1243124,...) )

我需要的是为一个字符串。我把那成UDP数据包。 我与sprintf的玩弄,但我没有C专家,所以任何帮助将是非常美妙的。

谢谢!

+1

检查的sprintf'的返回值()'有多少字符打印。 – timrau 2014-10-01 01:22:55

+0

期望输出字符串的确切格式是什么? – 2014-10-01 01:34:25

回答

2

最有效的方法是将每个元素迭代为snprintf到缓冲区中。

这是一个模拟Python的join()的函数。

#include <stdio.h> 

#define ARRAY_LEN(x)   (sizeof(x)/sizeof(x[0])) 

/** 
* Print an array of unsigned long long integers to a string. 
* Arguments: 
* buf  Destination buffer 
* buflen Length of `buf' 
* ar  Array of numbers to print 
* arlen Number of elements in `ar' 
* sep  Separator string 
* Returns: 
* The number of bytes printed 
*/ 
int join_ull(char *buf, int buflen, 
    unsigned long long ar[], int arlen, const char *sep) 
{ 
    int i; 
    char *p; 
    const char *end = buf + buflen; 

    /* While we have more elements to print, and have buffer space */ 
    for (i=0, p=buf; i<arlen && p<end; ++i) { 
     p += snprintf(p, end-p, "%llu%s", ar[i], 
      (i<arlen-1) ? sep : "");  /* Print separator if not last. */ 

     /* Note that p is advanced to the next place we want to print */ 
    } 

    return p-buf; 
} 


int main(void) 
{ 
    unsigned long long ar[] = {1, 2, 3}; 
    char buf[1024]; 

    join_ull(buf, sizeof(buf), ar, ARRAY_LEN(ar), " "); 
    printf("Output: \"%s\"\n", buf); 

    /* Test the buffer-too-small case */ 
    join_ull(buf, 4, ar, ARRAY_LEN(ar), " "); 
    printf("Output: \"%s\"\n", buf); 

    return 0; 
} 

结果:

Output: "1 2 3" 
Output: "1 2" 
+0

优雅!只是详细说明在问题中提到的'('')' – chouaib 2014-10-01 01:32:26

+0

@chouaib不确定OP *实际*是否需要'()'。 – 2014-10-01 01:34:41

+0

哈...好吧,那是行得通的,不过我只有一半了解它,但我会惹恼它的。非常感谢你! – beasts 2014-10-01 01:34:46