简体   繁体   English

如何在 C 中将格式化字符串作为单个参数传递?

[英]How to pass a formatted string as a single argument in C?

How would I go about formatting a string and passing it as a single argument in C?我将如何 go 关于格式化字符串并将其作为 C 中的单个参数传递? If I wanted to use sprintf() , I would have to create a variable first and then store the formatted result in there before passing the variable.如果我想使用sprintf() ,我必须先创建一个变量,然后在传递变量之前将格式化的结果存储在其中。 This feels messy.这感觉很乱。 Is there any way around this?有没有办法解决? Or is that how it should be done?还是应该这样做?

The " messy " part can be isolated into a helper myFmtFunction function, which builds the string then calls the real myFunction . 凌乱”的部分可以被隔离成一个助手myFmtFunction function,它构建字符串然后调用真正的myFunction The formatting helper could actually be reused for different myFunction targets, by passing an additional function pointer argument (though the sample code below does not do that, in order to keep it simpler).通过传递一个额外的 function 指针参数,格式化助手实际上可以用于不同的myFunction目标(尽管下面的示例代码没有这样做,以使其更简单)。

#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>

void myFunction(const char *msg)
{ printf("[myFunction] %s: %d\n", msg, rand() % 6 + 1); }

void myFmtFunction(const char *fmt, ...)
{
  // determine required buffer size 
  va_list args;
  va_start(args, fmt);
  int len = vsnprintf(NULL, 0, fmt, args);
  va_end(args);
  if(len < 0) return;

  // format message
  char msg[len + 1]; // or use heap allocation if implementation doesn't support VLAs
  va_start(args, fmt);
  vsnprintf(msg, len + 1, fmt, args);
  va_end(args);

  // call myFunction
  myFunction(msg);
}

int main() {
  const char s[] = "dice roll";
  const int n = 3;
  for(int i = 1; i <= n; i++)
    myFmtFunction("%s %d of %d", s, i, n);
  return 0;
}

Possible output :可能的 output

[myFunction] dice roll 1 of 3: 2
[myFunction] dice roll 2 of 3: 5
[myFunction] dice roll 3 of 3: 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM