编写自定义 FPrintF
Writing Custom FPrintF
我必须制作自己的fprintf
方法,但是通过将我的方法的执行时间与标准方法进行比较,我的方法几乎慢了 3 倍。我做错了什么?
void FPrintF(const char *aFormat, ...)
{
va_list ap;
const char *p;
int count = 0;
char buf[16];
std::string tbuf;
va_start(ap, aFormat);
for (p = aFormat; *p; p++)
{
if (*p != '%')
{
continue;
}
switch (*++p)
{
case 'd':
sprintf(buf, "%d", va_arg(ap, int32));
break;
case 'f':
sprintf(buf, "%.5f", va_arg(ap, double));
break;
case 's':
sprintf(buf, "%s", va_arg(ap, const char*));
break;
}
*p++;
const uint32 Length = (uint32)strlen(buf);
buf[Length] = (char)*p;
buf[Length + 1] = ' ';
tbuf += buf;
}
va_end(ap);
Write((char*)tbuf.c_str(), tbuf.size());
}
你做错了什么。
好吧,对于一个你正在使用sprintf来构造你的输出,它几乎可以做你想做的事情,这不是*printf系列函数所做的。 看看任何printf代码实现。
更好的是你为什么不使用它?
#include <cstdio>
#include <cstdarg>
namespace my {
void fprintf(const char *aFormat, ...)
{
va_list ap;
va_start(ap, aFormat);
(void)vprintf(aFormat, ap);
va_end(ap);
}
}
int main() {
my::fprintf("answerswer is %dn", 42);
return 0;
}
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何在自定义类中启用'auto loops'?
- 使用QJsEngine在Qt中注册自定义类型
- Qt自定义QPush按钮未显示在布局上
- 我如何自定义fprintf以启用禁用
- 编写自定义 FPrintF
- 添加带有自定义标准错误的 fprintf() 语句后,标准输出挂起