0

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?

David G
  • 94,763
  • 41
  • 167
  • 253
Monic92
  • 21
  • 5
  • 3
    `std::stringstream` is a rough equivalent, but not an exact one since it lacks the danger of buffer overflows. If you want to simulate that in C++, you can just do `std::string("")[100] = 'a';`. –  Jan 21 '14 at 23:54
  • For something like this with just one argument, `std::to_string` works well also. – chris Jan 21 '14 at 23:55
  • @chris, `to_string` is a fine choice if you're working in C++11 or later (which I usually am), but it's not available in C++03. Just a caveat. – Adam H. Peterson Jan 22 '14 at 00:10
  • this is my code char name[100]; sprintf(name,"E:/tigaouts/Debug/jari2.jpg",rank+42+size); how to make it in c++ – Monic92 Jan 22 '14 at 00:24

3 Answers3

4

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).

Adam H. Peterson
  • 4,511
  • 20
  • 28
  • how to change it if we use std::cout ? – Monic92 Jan 22 '14 at 00:05
  • 2
    @user3021930, I don't understand the question. But if you want to print the name out once you've constructed it, you can just write `cout << name << "\n";`. Alternatively, you could just stream it into `cout` rather than `oss` in the first place. – Adam H. Peterson Jan 22 '14 at 00:06
3

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;
SirDarius
  • 41,440
  • 8
  • 86
  • 100
0

or you can use boost format library

cout << boost::format("jari%1%.jpg") % (rank + 42 + size)
pm100
  • 48,078
  • 23
  • 82
  • 145