7

In javascript I can format a string using template string

const cnt = 12;
console.log(`Total count: ${cnt}`);

if I work with python I can use the f-string:

age = 4 * 10
f'My age is {age}'

But, if I working with C++(17) what is the best solution to do this (if it is possible)?

th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50
  • 4
    Install [libfmt](https://github.com/fmtlib/fmt), then you can do `fmt::print("Total count: {}", cnt);`. – HolyBlackCat Oct 08 '20 at 20:26
  • 1
    `std::cout << "Total count: " << cnt << std::endl;` Works with stringstream too – Vlad Feinstein Oct 08 '20 at 20:26
  • I don't know what's the problem well. but if u want to use numbers with the strings here is an example. `size_t age = 40; std::string str = "My age is "+ std::to_string(age);` – asmmo Oct 08 '20 at 20:27

3 Answers3

13

I think the simpler way is std::to_string:

std::string str = "My age is ";
str += std::to_string(age);

std::ostringstream also works nicely and can be useful as well:

With this at the top of your source file

#include <sstream>

Then in code, you can do this:

std::ostringstream ss;
ss << "My age is " << age;
std::string str = ss.str();
selbie
  • 100,020
  • 15
  • 103
  • 173
10

you can use sprintf

sprintf(dest_string, "My age is %d", age).

but using sprintf will rase an error, so best use snprintf:

snprintf(dest_string, size , "My age is %d", age);

where size is the is the maximum number of bytes.

David Frucht
  • 181
  • 1
  • 8
  • 11
    Welcome to StackOverflow David. Unfortunately, answers in "C" for questions tagged as C++, while valid, tend to get downvoted. (Disclaimer: I didn't downvote, but have been a victim of this culture as well) – selbie Oct 08 '20 at 20:35
  • 8
    While this solution *can* work in C++, it is based on C and is not a good solution for C++, as it lacks adequate type checking and buffer overflow checking, things that C++ has solved with other solutions. – Remy Lebeau Oct 08 '20 at 20:37
  • Which other solution? Interesting that *A Tour of C++ (Third edition)* of Stroustrup (so a very short and essential guide of C++ to C++23) explains also such C method (but none of the rest of c library). Until std::format is in wide use (still not available on many compilers now), there is no perfect C++ solution. I think we should trust Stroustrup. – Giacomo Catenazzi Jun 28 '23 at 14:25
0

If you want to write to stdout:

const int cnt = 12;
std::cout << "Total count: " << cnt << "\n";

Writing to any other stream works similar. For example replace std::cout by a std::ofstream to write to a file. If you need the formatted string:

std::ostringstream oss;
oss << "Total count: " << cnt << "\n";
std::string s = oss.str();
std::cout << s;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185