How to format dynamic string in c++

Since 4.20, the FString::Printf function does not accept non-literal format string, it will report error
“The formatting string must now be a TCHAR string literal.”

The similar comments can found in unrealstring.h
But our game heavily depended on formating dynamic string. We config all the gossip scripts and description text in config file. When display the string, we read back them and replace the “%s”, or “%d” to the final value, such as name of npc or items.

So, as FString::Printf support literal format strong now, is there more appropriate way to do this job now?

Any update on this?

Hi!
Test on UE4.25.3 FString::Format:

const int32 MyInt = 12;
const float MyFloat = 0.12f;
const FString MyString = FString(TEXT("MyStringValue"));

//const FString MyStringPrintf = FString::Printf(TEXT(“MyStringPrintf: {0}, {1}, {2}”));

const FString MyStringPrintf = FString(TEXT(“MyStringPrintf: {0}, {1}, {2}”));

const FString MyStringFormatted = FString::Format(*MyStringPrintf, { MyInt, MyFloat, MyString });

UE_LOG(LogTemp, Warning, TEXT("MyStringFormatted: %s"), *MyStringFormatted);
// LogTemp: Warning: MyStringFormatted: MyStringPrintf: 12, 0.120000, MyStringValue

Hope this helps!

2 Likes

Yup, that’s what I was looking for! Thanks