C++ equivalent of sprintf?

C++Printf

C++ Problem Overview


I know that std::cout is the C++ equivalent of printf.

What is the C++ equivalent of sprintf?

C++ Solutions


Solution 1 - C++

std::ostringstream

Example:

#include <iostream>
#include <sstream> // for ostringstream
#include <string>

int main()
{
  std::string name = "nemo";
  int age = 1000;
  std::ostringstream out;  
  out << "name: " << name << ", age: " << age;
  std::cout << out.str() << '\n';
  return 0;
}

Output:

name: nemo, age: 1000

Solution 2 - C++

Update, August 2019:

It looks like C++20 will have std::format. The reference implementation is {fmt}. If you are looking for a printf() alternative now, this will become the new "standard" approach and is worth considering.

Original:

Use Boost.Format. It has printf-like syntax, type safety, std::string results, and lots of other nifty stuff. You won't go back.

Solution 3 - C++

sprintf works just fine in C++.

Solution 4 - C++

Here's a nice function for a c++ sprintf. Streams can get ugly if you use them too heavily.

std::string string_format(const std::string &fmt, ...) {
    int size=100;
    std::string str;
    va_list ap;

    while (1) {
        str.resize(size);
        va_start(ap, fmt);
        int n = vsnprintf(&str[0], size, fmt.c_str(), ap);
        va_end(ap);
   
        if (n > -1 && n < size) {
            str.resize(n); // Make sure there are no trailing zero char
            return str;
        }
        if (n > -1)
            size = n + 1;
        else
            size *= 2;
    }
}

In C++11 and later, std::string is guaranteed to use contiguous storage that ends with '\0', so it is legal to cast it to char * using &str[0].

It has been pointed out that variadic arguments are not supposed to follow pass-by-reference, and c++ is good about not copying strings if it doesn't have to. In that case, this fixes it.

std::string string_format(std::string fmt, ...) {

Solution 5 - C++

You can use iomanip header file to format the output stream. Check this!

Solution 6 - C++

Depending on what exactly you plan on sprintf()ing, std::to_string() might be useful and more idiomatic than other options:

void say(const std::string& message) {
 // ...
}

int main() {
  say(std::to_string(5));
  say("Which is to say " + std::to_string(5) + " words");
}

The main advantage of std::to_string(), IMHO, is that it can be extended easily to support additional types that sprintf() can't even dream of stringifying - kind of like Java's Object.toString() method.

Solution 7 - C++

Use a stringstream to achieve the same effect. Also, you can include <cstdio> and still use snprintf.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlital maatukView Question on Stackoverflow
Solution 1 - C++Vijay MathewView Answer on Stackoverflow
Solution 2 - C++janmView Answer on Stackoverflow
Solution 3 - C++Steve RoweView Answer on Stackoverflow
Solution 4 - C++Erik AronestyView Answer on Stackoverflow
Solution 5 - C++vinkrisView Answer on Stackoverflow
Solution 6 - C++GussView Answer on Stackoverflow
Solution 7 - C++regalityView Answer on Stackoverflow