Jack Avante
Jack Avante

Reputation: 1595

How does one correctly format a string on output with variables in C++ 17?

I'm wondering what is the efficient and smart way to output a string to console with variables. I know in C++20 there is std::format which makes this easy, but I'm unsure about C++17.

For example, as it could be done in C++20:

#include <iostream>
#include <string>
#inclide <format>

int main(){

    int a = 13;
    int b = 50;
    std::string out_str = std::format("The respondents of the survey were {}-{} years old.", a, b);

    std::cout << out_str << std::endl;

    return EXIT_SUCCESS;

}

Is there a nice way to do it akin to the example above in C++17?.. Or do I simply have to separate out different parts of the string and variables?

Upvotes: 5

Views: 7797

Answers (1)

lubgr
lubgr

Reputation: 38325

std::cout << "The respondents of the survey were " << a << "-" << b
   << " years old\n";

If you find that verbose and/or annoying, use fmtlib as a placeholder for std::format. Or go old-school with

#include <cstdio>

std::printf("The respondents of the survey were %d-%d years old.\n", a, b);

That is not type-safe, but when the format string stays a literal, recent compilers are quite good at pointing you towards non-matching format specifiers and arguments.

Upvotes: 6

Related Questions