[英]C++ Best Way Of Outputting Formatted Variable Argument Lists
This is my current function which works but is not type safe and can get annoying sometimes. 这是我当前的功能,但功能不安全,有时会很烦人。
void Debug::Log(LogLevel level, const char* format, ...)
{
va_list args;
va_start(args, format);
cout << "[" << LogLevelToString(level) << "]\t";
vprintf(format, args);
va_end(args);
cout << endl;
}
As you can see I would like for the arguments passed in to be formatted by the format specified. 如您所见,我希望传入的参数以指定的格式进行格式化。 I know std::cout has formatting capabilities but I haven't found anything which explains how it can be implemented with the C va_list.
我知道std :: cout具有格式化功能,但是我还没有找到任何能解释如何使用C va_list实施的内容。
Basically the main points are: I want to keep the the same behavior but with a type safe more modern method, I need to std::cout so I can easily redirect output to file or where ever I need to. 基本上,主要要点是:我想保持相同的行为,但是使用类型安全的更现代的方法,我需要std :: cout,以便可以轻松地将输出重定向到文件或任何需要的位置。
Helpful points: from the format I can determine how many parameters where passed in, is there a way to loop through va_list arguments so I can pass them to cout individually? 有用的要点:从格式中,我可以确定传入了多少个参数,有没有办法遍历va_list参数,以便我可以将它们分别传递给cout?
Thanks 谢谢
For easy redirection, you can certainly use vfprintf()
. 为了方便重定向,您当然可以使用
vfprintf()
。 For individual control/cout of each argument, I think the only way is to va_arg()
through the list using the correct type, ie an_int = va_arg(the_va_list, int);
对于每个参数的单独控制/提示,我认为唯一的方法是使用正确的类型遍历列表
va_arg()
,即an_int = va_arg(the_va_list, int);
, a_double = va_arg(the_va_list, double);
,
a_double = va_arg(the_va_list, double);
, and so on. , 等等。 I haven't tried but I think
va_arg
will do the proper increment on the memory using the type
passed to it. 我没有尝试过,但我认为
va_arg
将使用传递给它的type
在内存上做适当的增量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.