有没有办法直接在函数参数中格式化字符串而不是使用临时字符串? [英] Is there a way to format a string directly within a functions arguments instead of using a temporary string?

查看:35
本文介绍了有没有办法直接在函数参数中格式化字符串而不是使用临时字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受字符串(字符数组)作为参数的函数.

I have a function that accepts a string (char array) as its argument.

void enterString(char * my_string);

在使用这个函数时,我经常发现自己想要输入格式化的字符串.我使用 sprintf 来做到这一点.但是,每次都必须创建一个临时字符串有点烦人:

When using this function, I often find myself wanting to input formatted strings. I use sprintf to do this. However, It's kind of annoying that I have to create a temporary string every time:

char temp_str[100];
sprintf(temp_str, "My lucky number = %d", 11);
enterString(temp_str);

有什么方法可以在函数参数中直接格式化字符串,这样我就不必每次都创建一个临时字符串?类似的东西:

Is there any way to directly format a string within a functions arguments so I don't have to create a temporary string every time? Something like:

enterString("My lucky number = %d", 11);

谢谢

推荐答案

您不能在 C 中执行此操作(与 Python 等其他语言不同,它们具有使用 % 运算符或 str.format 函数).

You cannot do this in C (unlike other languages like python which have built-in formatting for string with the % operator or str.format function).

但是由于您的方法看起来像是要打印带有可变参数的格式化消息,您可以使用可以接受 va_listvfprintf参数,因此您可以将可变参数传递给内部函数.

But since your approach looks like you want to print a formatted message with variable arguments, you could use vfprintf that can accept a va_list argument, so you can transfer your variable arguments to your inner function.

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

void enterString(const char *format,...)
{

  va_list argptr;
  va_start(argptr, format);
  vfprintf(stdout, format, argptr);
  va_end(argptr);
  // rest of the processing here
}

int main()
{
   enterString("My lucky number = %d", 11);
   return 0;
}

printf 相比,这并没有带来太多,但是现在你有了这个,您可以添加对详细"模式的检查、登录到文件、打印前缀、日期、...在消息之前等...

This doesn't bring a lot compared to printf, but now that you have this, you can add a check for "verbose" mode, log to a file, print a prefix, date, ... before the message, etc...

我在 musashi 680x0 模拟器(在 m68kfpu.c 中)中找到了这个确切的代码

I found this exact code in the musashi 680x0 emulator (in m68kfpu.c)

static void fatalerror(char *format, ...) {
  va_list ap;
  va_start(ap,format);
  vfprintf(stderr,format,ap);
  va_end(ap);
  exit(1);
}

(我不得不修复代码中错误的fprintf,但除此之外,我们看到了一个直接的应用程序:该函数用于打印变量格式的错误消息,然后退出操作系统)

(I had to fix the wrong fprintf that was in the code, but apart from that, we see a direct application: this function is used to print a variable formatted error message, then quit to the operating system)

这篇关于有没有办法直接在函数参数中格式化字符串而不是使用临时字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆