2

Is there a way to use sprintf() without a predefined variable?

Instead of:

char buffer[80];
sprintf(buffer, "%d",i );
myfunc(buffer);

I'd like to use:

myfunc(stringformat("%d",i));

Writing C++, mean C-like functions without OOP.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jsmith
  • 175
  • 1
  • 10
  • "Is there a way to use sprintf without a predefined variable?" - No. That's what you get for writing C in C++. – eesiraed Jun 14 '20 at 04:28
  • In standard C++ you can use `stringstream`, but it won't be the same. Microsoft's `CString` class provides a `Format` function that does what you want. – Mark Ransom Jun 14 '20 at 04:29
  • `std::to_string` also does what you want (in this case). – john Jun 14 '20 at 04:32
  • Boost's [format library](https://www.boost.org/doc/libs/1_73_0/libs/format/doc/format.html) also does something similar. – john Jun 14 '20 at 04:34
  • Not out of the box, but you can roll your own, see for example [std::string formatting like sprintf](https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf). – dxiv Jun 14 '20 at 04:35

1 Answers1

0

Do you necessarily need to use same formatting rules as in printf/sprintf? If so there is no standard library function to do that and you'll need to probably write your own using snprint under the hood (in edge cases for large format strings you would probably need to iterate over increasingly large buffer sizes or just limit maximum supported size of the output).

If you need something similar, but with different formatting - earliest it appears in standard library is C++20: std::format. There are also alternatives to standard library e.g. boost::format, folly::sformat.

Also in many cases using stringstream is more convenient.

Alexander Pivovarov
  • 4,850
  • 1
  • 11
  • 34