printf返回一个字符串
是否有类似printf的函数可以返回字符串而不是打印它? 我有一个以某种颜色打印字符串的函数,但它必须是字符串文字,而不是接受像printf这样的变量。
// Function declaration (Assums YELLOW and NORMAL are the unix constants for terminal colors void pYellow(char *str) { printf("%s%s%s", YELLOW, str, NORMAL); } //Function call void pYellow("This is a string");
如果我想用变量打印颜色,它就不会起作用。 像pYellow("Num: %d", 42);
会出错,因为它的参数太多了。 做pYellow(printf("String"));
也不会工作。
TL:DR我想知道是否有一个printf方法返回一个字符串而不是打印它。
使用snprintf
:
int snprintf(char *str, size_t size, const char *format, ...);
-
str
是你分配的缓冲区(例如malloc()
) -
size
是该缓冲区的大小 - 在调用之后,格式化的字符串存储在
str
。 - 还有
sprintf
, 从不使用它
您还可以使用v*printf
系列函数创建自己的printf
v*printf
的函数。 最简单的例子:
#include // required for va_list, va_start, va_end void customPrintf(const char* format, /* additional arguments go here */ ...) { va_list args; va_start(args, format); // set color here (for example) vprintf(format, args); // reset color va_end(args); }