HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

std::string formatting like sprintf

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
formattingsprintflikestdstring

Problem

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

Code Snippets

char buff[100];
  snprintf(buff, sizeof(buff), "%s", "Hello");
  std::string buffAsStdStr = buff;
std::ostringstream stringStream;
  stringStream << "Hello";
  std::string copyOfStr = stringStream.str();

Context

Stack Overflow Q#2342162, score: 421

Revisions (0)

No revisions yet.