转换为字符串

基本类型 / 数字 / 整型

int number = 42;

char s1[12];
snprintf(s1, sizeof s1, "%d", number);
//s1 is "42"

char s2[12];
snprintf(s2, sizeof s2, "%03d", number);
//s2 is "042"

//snprintf with nullptr only counts the length,
//so the buffer can be allocated exactly
int value = -12345;
int len = snprintf(nullptr, 0, "%d", value);
//len is 6
char *s3 = malloc(len + 1);
snprintf(s3, len + 1, "%d", value);
//s3 is "-12345"

printf("s1 is %s\n", s1);
printf("s2 is %s\n", s2);
printf("len is %d\n", len);
printf("s3 is %s\n", s3);
free(s3);