在 C 中是否有一种方法可以像在 printf
中一样格式化字符串,但将其存储在变量中?我正在尝试将其用于系统调用,因此我可以在调用中包含一个变量。
最佳答案
您可以使用sprintf
(或 C99/C11 中的 snprintf
)在使用字符串之前格式化它。
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
示例:
// Use the value of an integer 'n' as argument in 'perror' (C99).
#include <limits.h>
#include <stdio.h>
char argument[sizeof(int) * CHAR_BIT + 1];
snprintf(argument, sizeof argument, "%d", n);
perror(argument);
关于我可以像 printf 一样存储格式化字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969397/