106

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

What is the C++ equivalent of sprintf?

7 Answers 7

77

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
7
  • 4
    I don't think that sprintf writes to stdout. I would remove the insertion statement above.
    – khatchad
    May 18, 2011 at 1:08
  • 108
    How is this even remotely similar to sprintf (...)? You cannot format the data arbitrarily, you have to rely on the type being known when you feed it into the stream using the << operator. Feb 27, 2014 at 15:40
  • 1
    I need to agree with @AndonM.Coleman about this one. This is not really a sprintf replacement. This would be more like that, but this is Qt. Mar 6, 2014 at 17:25
  • 1
    as @vinkris says in his answer, iomanip achieves formatting. Instead of printing to stdoit, I would say "result = out.str()".
    – Dmitri
    Oct 3, 2014 at 4:09
  • sprintf / snprintf allows formating and printing to a user allocated character array, may be on stack. In case of snprintf(), it ensures there is no overrun. Here we are allocating memory multiple times and the caller has no direct access it. Have to convert to a string to get the output. An std::ostream with a custom std::streambuf, which takes user buffer would be a better match - of course construction/destruction of ostream/streambuf adds more in-efficiency.
    – MGH
    Aug 9, 2018 at 20:39
44

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.

4
  • 21
    ... unless you are concerned about the size of your executable.. :P
    – pradyunsg
    Sep 7, 2014 at 15:11
  • How much of an impact would this have? The Boost dependency would be header-only, no linking, correct? Nov 9, 2017 at 19:25
  • 1
    @KenWilliams Yes, Boost.Format is header only. A simple "hello, world" test on my Mac increases from 10kB to 78kB. In a real project the extra size will be amortised across compilation units (give the right linker options), and the type safety brings other benefits.
    – janm
    Nov 9, 2017 at 21:14
  • When executable size bloats, always try to use shared libraries! Feb 11, 2022 at 16:18
19

sprintf works just fine in C++.

2
  • 7
    I think the OP meant STL rather than C++. Aug 1, 2013 at 8:26
  • 5
    sprintf requires you to allocate the character buffer. I would like something like the "append" method of "std::string" that allows me to add formatted data, and taking care of allocating behind the scenes. Mar 4, 2015 at 18:52
11

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

std::string string_format(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].

10
  • Very nice solution! I've adapted it here: stackoverflow.com/a/3742999/15161 to more closely fit sprintf-usage.
    – slashmais
    Dec 27, 2012 at 18:07
  • 12
    Illegal, though: (char*) str.c_str() casts away const.
    – MSalters
    Mar 18, 2013 at 12:36
  • also there's buffer overflow problem lurking Nov 4, 2015 at 12:56
  • @MSalters Correct. There's a legal way to do that in C++11.
    – Catherine
    Dec 28, 2015 at 11:25
  • @whitequark: Feel free to add that as an answer. On Stack Overflow, good question remain open to allow new answers.
    – MSalters
    Dec 28, 2015 at 12:50
7

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

1
  • Why did somebody downvote this? Isn't iomanip the pure-C++ way of achieving formatting in streams? I think the goal here is to avoid storing data in C-style strings, which is achieved with iomanip.
    – Dmitri
    Oct 3, 2014 at 4:06
2

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.

-1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.