C++ 将参数转换为字符串

C++ 将参数转换为字符串,c++,string,variadic-macros,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_A

我试图重新定义一个变量宏,用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)
#定义打印级别(级别,…)do{\
if(debug\u components.debug\u COMPONENT>=级别)\

{std::string argString;sprintf(argString,_uva_uargs_uu);std::cout
sprintf
需要一个额外的参数,即将输出写入其中的数据缓冲区。如果不进行更改以提供缓冲区,则无法将
printf
替换为
sprintf
。它也不会返回字符串指针,因此无法将结果分配给
std::string
,并期望它正常工作。I如果您操作不安全(假设缓冲区长度最大),请执行以下简单操作:

#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)
#定义打印级别(级别,…)do{\
if(debug\u components.debug\u COMPONENT>=级别)\
{ 
char-buf[1024];

sprintf(buf,_VA_ARGS_;);std::cout我使用sprintf时出错。下面是正确的代码:

char argString[1024]; sprintf(argString, __VA_ARGS__);

现在argString保存了VA_ARGS的值

小心点,snprintf为第一个参数设置了缓冲区。仍然不起作用。请参阅上面编辑的代码;现在我得到了以下错误:候选函数不可行:没有从'std::string'(也称为'basic_string'的已知转换)为第一个参数extern int sprintf设置“char*\uu restrict”(char*\uuuuu restrict,永远不要使用宏。使用函数。为了效率起见,希望它们内联?让它有内部链接,使其成为
静态
非成员函数。你不能
sprintf
snprintf
std::string
。你不能在宏中正确地做到这一点。快告诉我吧!谢谢。