troubleshooting Question

How to print into std::string like sprintf using C++11?

Avatar of ugeb
ugebFlag for United States of America asked on
C++
12 Comments2 Solutions14845 ViewsLast Modified:
In the past when I've needed a formatted string, I've created a char buffer and then did sprintf into that buffer.  Now that C++ has the std string class, I'd like to use it more, but it doesn't seem to play nice all the time.

I know I can still create the buffer, sprintf into that buffer and then convert to string, but is there a better way?  For example, if I have the following (junk code):

int i=1;
int j=4;
char buf[50];
sprintf(buf,"Pair (%d,%d) = %f\n",i,j,(double)i/j);

outputs:
Pair (1,4) = 0.25

How can I print that string directly into a std::string instead of going through a char buffer?


Using: C++11, Visual Studio 2013
ASKER CERTIFIED SOLUTION
evilrix
Senior Software Engineer (Avast)

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros