Mar*_*Rob 2 c string string-formatting
在 C 中有没有办法可以像在 中那样格式化字符串printf,而是将其存储在变量中?我试图将它用于系统调用,因此我可以在调用中包含一个变量。
您可以使用sprintf(或snprintf在 C99/C11 中)在使用之前格式化您的字符串。
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
Run Code Online (Sandbox Code Playgroud)
例子:
// 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);
Run Code Online (Sandbox Code Playgroud)