Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 编写自定义FPrintF_C++_File_Printf_Game Engine_Execution Time - Fatal编程技术网

C++ 编写自定义FPrintF

C++ 编写自定义FPrintF,c++,file,printf,game-engine,execution-time,C++,File,Printf,Game Engine,Execution Time,我必须创建自己的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++) {

我必须创建自己的
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] = '\0';
      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("answer is %d\n", 42);
    return 0;
}
#包括
#包括
名称空间我的{
无效fprintf(常量字符*格式,…)
{
va_列表ap;
va_启动(ap,aFormat);
(无效)vprintf(格式,ap);
va_端(ap);
}
}
int main(){
my::fprintf(“答案是%d\n”,42);
返回0;
}

errr您能修改问题的格式吗?printf写得很好:)。许多编译器都支持编译时。您正在使用sprintf将数据写入buf。然后sprintf必须解析格式并进行输出
sprintf(buf,“%s”,va_arg(ap,const char*)正在播放堆栈溢出火焰。如果它是C++,为什么要标记C?但是我需要把BUF写入我的文件。我看到标准fprintf接收到一个文件*,我的自定义fprintf位于FileHandle类中,应该将buf写入最终文件。如果需要将其写入文件,可以使用
vsnprintf
创建字符串或
vfprintf
将其直接转储到文件中。