user29337117
user29337117

Reputation:

C++ format specifiers in custom functions

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.

Upvotes: -3

Views: 114

Answers (2)

Proteus
Proteus

Reputation: 558

You are correct, the "three dots" parameter is what you need. You can use vprintf:

#include <iostream>
#include <cstdarg> // For va_list, va_start, va_end
#include <cstdio>  // For vprintf

void output(const char* format, ...) {
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}

int main() {
    int a = 123;
    output("The number is %d %d\n", a, 456);
    return 0;
}

If you're using C++20 or higher, you can also look at std::format for modern and type-safe placeholding.

Upvotes: 2

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38862

Yes, you can use vprintf for such purposes.

void output(std::string fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vnprintf(fmt.c_str(), args);
    va_end(args);
    std::cout << '\n';
}

The strong advice: use std::format since C++20 or {fmt} library.

Upvotes: 0

Related Questions