我正在尝试重新定义可变参数宏以使用 cout 而不是 printf。原始代码如下:
#define LOGE(...) PRINT_LEVEL(1, __VA_ARGS__);
#define PRINT_LEVEL(level,...) do { \
if (debug_components.DEBUG_COMPONENT >= level) \
{ printf("[%s]: ", levels_strings[level-1]); printf(__VA_ARGS__); printf("\n"); } \
}while(0)
我将其转换为以下内容以使用 cout 而不是 printf:
#define PRINT_LEVEL(level,...) do { \
if (debug_components.DEBUG_COMPONENT >= level) \
{ std::string argString; sprintf(argString, __VA_ARGS__); std::cout << "[" << levels_strings[level-1] << "]" << argString << "\n";} \
}while(0)
出于某种原因,__VA_ARGS__
可以与 printf 配合使用,但不能与 sprintf 配合使用。它也不适用于 cout。我想知道将 __VA_ARGS__ 转换为字符串的正确方法,或者如果失败,则使用 cout 将其打印出来的正确方法。
最佳答案
sprintf
需要一个额外的参数,即要写入输出的数据缓冲区。如果不进行更改以提供该缓冲区,则无法将 printf
替换为 sprintf
。它也不会返回指向字符串的指针,因此您不能将结果分配给 std::string 并期望它起作用。如果您的操作不安全(假设最大缓冲区长度),那么简单如下:
#define PRINT_LEVEL(level,...) do { \
if (debug_components.DEBUG_COMPONENT >= level) \
{
char buf[1024];
sprintf(buf, __VA_ARGS__); std::cout << "[" << levels_strings[level-1] << "]" << buf << "\n";} \
}while(0)
可以工作(并且通过截断,如果不能通过 snprintf
可靠地完成,则可以安全地完成),但如果您无论如何都使用 C++ 类型,您可能需要查看 a non-printf
-y solution
关于c++ - 将 __VA_ARGS__ 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41288780/