Home > Enterprise >  What is the correct way to use fmt::sprintf?
What is the correct way to use fmt::sprintf?

Time:11-20

I'm trying to optimize my software and to do that I need to change the way I store and draw things.

Many people say that fmt is way faster than iostream at doing those things, yet I'm sitting here and trying to understand what I did wrong.

The old code is working:

auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos)
sprintf(name, "AI [%dm]", dist);

The new one isn't:

auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos)
fmt::sprintf("AI [%dm]", dist);

What am I doing wrong?

CodePudding user response:

As @NathanPierson mentioned in comments, fmt::sprintf() return a std::string, which you are ignoring. fmt::sprintf() does not fill a char[] buffer (not that you are passing one in to it anyway, like you were with ::sprintf()).

Change this:

char name[0x64];
fmt::sprintf("AI [%dm]", dist);

To this:

std::string name = fmt::sprintf("AI [%dm]", dist);

And then you can use name as needed. If you need to pass it to a function that expects a (const) char*, you can use name.c_str() or name.data() for that purpose.

CodePudding user response:

Many people say that fmt is way faster than iostream at doing those things, yet I'm sitting here and trying to understand what I did wrong.

In addition to Remy Lebeau's correct answer, there's another point. You mentioned speed as a consideration. In that case, you may want avoid constructing an std::string, and use fmt::format_to_n() (or std::format_to_n) to format into your char buffer directly:

auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos) {
    fmt::format_to_n(name, 0x64, "AI [{}m]", dist);
}

Unfortunately, I don't think fmt has a function which targets an existing buffer and uses printf format specifiers.

  • Related