c++ - 将 __VA_ARGS__ 转换为字符串

标签 c++ string variadic-macros

我正在尝试重新定义可变参数宏以使用 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/

相关文章:

c - 这是检查可变宏参数列表是否为空的有效方法吗?

c++ - Linux/Ubuntu 中的 OpenCV 安装

c++ - OpenCV 卡尔曼滤波器,从 std::vector 中删除

c++ - C++ 中的威尔逊定理,输出不正确?

c++ - 在 C++ 中搜索字符串对象数组的最有效方法?

c - 用于打印可变参数的宏,可以选择无参数

c++ - XOR 交换算法中运算符的未定义行为?

python - UTF-8 列的 SQLAlchemy 结果是 'str' 类型,为什么?

string - 当 $STRING 以 "\t\t"结尾时,如何让 split(/\t/, $STRING) 检测空值?

c++宏导入基模板类的所有名称