What is the C++ equivalent of the code below?
sprintf(name,"jari%d.jpg",rank+42+size);
help me how to change it to c++. can anyone help me?
What is the C++ equivalent of the code below?
sprintf(name,"jari%d.jpg",rank+42+size);
help me how to change it to c++. can anyone help me?
I would suggest an ostringstream
:
string name;
{
ostringstream oss;
oss << "jari" << (rank+42+size) << ".jpg";
name = oss.str();
}
Details: To use this solution, you'll want #include <sstream>
and pull ostringstream
into scope with using std::ostringstream;
(or just use std::ostringstream
directly qualified).
The equivalent would be:
#include <sstream>
std::ostringstream s;
s << "jari" << rank + 42 + size << ".jpg";
std::string name = s.str();
Not exactly equivalent in terms of data types, since the final result is a std::string
instead of a char*
, but the most idiomatic.
Outputting the formated string directly is even simpler:
std::cout << "jari" << rank + 42 + size << ".jpg";
Alternatively, there is also the Boost Format library that offers similar functionality:
#include <boost/format.hpp>
boost::format formatter("jari%1%.jpg");
formatter % rank+42+size;
std::string name = formatter.str();
or to directly output the string:
std::cout << boost::format("jari%1%.jpg") % rank+42+size;
or you can use boost format library
cout << boost::format("jari%1%.jpg") % (rank + 42 + size)