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

1

5

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?

Sauls answered 29/9, 2020 at 14:8 Comment(5)
FYI: format doesn't let you do that. C++ isn't Python, so you shouldn't expect it to do what Python does.Stallfeed
How does it not?.. I have tried C++ 20 using the format library (en.cppreference.com/w/cpp/utility/format) with good success. It worked well.Sauls
It doesn't let you do what you posted. It can't "reach out" and find a and b. It can do Printf-style formatting, where you would have "{}-{}" in the string, and you pass a and b to the format function. But format can't find a and b on its own.Stallfeed
Ah I understand what you mean. It was merely a demonstrative example to pass on my thoughts. I will edit the code and post accordinglySauls
Xcode 15.3 includes support for std::format.Solidary
P
6
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.

Prevaricator answered 29/9, 2020 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.