std::string formatting like sprintf

Max Frai picture Max Frai · Feb 26, 2010 · Viewed 893.5k times · Source

I have to format std::string with sprintf and send it into file stream. How can I do this?

Answer

Doug T. picture Doug T. · Feb 26, 2010

You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

  char buff[100];
  snprintf(buff, sizeof(buff), "%s", "Hello");
  std::string buffAsStdStr = buff;

But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:

  std::ostringstream stringStream;
  stringStream << "Hello";
  std::string copyOfStr = stringStream.str();