Is it possible in C++ to use format specifiers in a custom function? Like as in the printf() statement, and how you can use e.g. '%d' to insert an int variable:
printf("The number is %d", num);
But is there a way I can do this with my own function, in C++? Like this:
void output(std::string message)
{
std::cout << message << '\n';
}
int main()
{
int num = 123;
output("The number is %d", num);
return 0;
}
I tried searching it up, but couldn't really find any result stating that this is possible, so it probably isn't.
I did see something with three dots in a function parameter, a variadic function, but I couldn't figure out if that was what I'm searching for.
Edit: I feel a little bad, maybe I could've just found it with searching a bit better (I didn't know variadic functions were the way to go). See https://en.cppreference.com/w/cpp/utility/variadic. I'm sorry for that.
std::formatter
%d
with value ofnum
. Whatprintf
does is it takes aconst char*
and variadic arguments, assumes thatconst char*
contains a valid format string and then reads it, finding every%
and trying to replace it with next from variadic arguments. If you want to replicate that function, you would need to do the same.std::print("The number is {}", num);
. std::print