[SOLVED] std::string formatting like sprintf

Issue

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

Solution

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();

Answered By – Doug T.

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *