Best way to format string in C++

12,875

Solution 1

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.

Solution 2

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();
Share:
12,875
th3g3ntl3man
Author by

th3g3ntl3man

¯\_(ツ)_/¯

Updated on June 15, 2022

Comments

  • th3g3ntl3man
    th3g3ntl3man almost 2 years

    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)?

  • Saurav Seth
    Saurav Seth over 3 years
    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)
  • Remy Lebeau
    Remy Lebeau over 3 years
    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.