根据 top answer on SO,这是我应该在 C 中将整数转换为字符串的方法:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <math.h>
#define digits(x) ((int)((ceil(log10(abs(x)))+1)*sizeof(char)))
int main () {
int a = 345908220;
long b = 23094809284358;
unsigned int c = 3456789234;
uint8_t d = 242;
int64_t e = -840958202029834;
int dstr_len = digits(a) + digits(b) + digits(c) +
digits(d) + digits(e) + 5;
char dstr[dstr_len];
sprintf(dstr, "%d %ld %u %u %" PRIu64, a, b, c, d, e);
printf("%s\n", dstr);
return 0;
}
但是,这似乎效率低得离谱。我必须将我的程序链接到 libmath,并对我要打印的每个整数进行三个 数学调用。另请注意,我必须将 5
添加到我的缓冲区,而不仅仅是 1
用于 NUL
终止符,方法是计算格式中的空格数字符串。这似乎也容易出错,并可能导致缓冲区溢出。
那么,是否有任何好的标准函数可以为我计算缓冲区的大小?
我正在尝试编写安全的 C。
最佳答案
如果您的编译器有可用的snprintf()
,您可以请求格式化的缓冲区长度,然后相应地进行分配:
int dstr_len = snprintf(NULL, 0, "%d %ld %u %u %" PRIu64, a, b, c, d, e) + 1;
char dstr[dstr_len];
//
// NOTE: variable-length arrays are NOT supported in all compilers!
// A more portable solution is:
//
// char *dstr = malloc(sizeof(char) * dstr_len);
snprintf(dstr, dstr_len, "%d %ld %u %u %" PRIu64, a, b, c, d, e);
// free(dstr);
关于安全地将int转换为C中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25691227/