[英]c function to return formatted string
I would like to do something like this: 我想做这样的事情:
writeLog(printf("This is the error: %s", error));
so i am looking for a function which returns a formatted string. 所以我正在寻找一个返回格式化字符串的函数。
There is no such function in the standard library and there will never be one in the standard library. 标准库中没有这样的功能,标准库中永远不会有这样的功能。
If you want one, you can write it yourself. 如果你想要一个,你可以自己写。 Here's what you need to think about: 以下是您需要考虑的事项:
Given no such function exists, consider a slightly different approach: make writeLog
printf-like, ie take a string and a variable number of arguments. 如果不存在这样的函数,请考虑稍微不同的方法:使writeLog
print,即获取字符串和可变数量的参数。 Then, have it format the message internally. 然后,让它在内部格式化消息。 This will solve the memory management issue, and won't break existing uses of writeLog
. 这将解决内存管理问题,并且不会破坏writeLog
现有用途。
If you find this possible, you can use something along these lines: 如果您发现这可能,您可以使用以下内容:
void writeLog(const char* format, ...)
{
char msg[100];
va_list args;
va_start(args, format);
vsnprintf(msg, sizeof(msg), format, args); // do check return value
va_end(args);
// write msg to the log
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.