Advertisement
notinlist

Convenient printf usage in C++ via snprintf wrapping

Feb 23rd, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream> // Required for main
  2.  
  3. #include <string>
  4. #include <vector>
  5. #include <cstdio>
  6.  
  7. /**
  8.  * Creates a string from a printf format and the arguments by wrapping snprintf.
  9.  * Uses on-stack buffer under 100 total length, allocates on heap otherwise.
  10.  */
  11. template<typename ... Params>
  12. std::string pformat(char const *fmt, Params&& ... args)
  13. {
  14.   const int BS = 100;
  15.   char buf[BS];
  16.   int cap = std::snprintf(buf, BS, fmt, std::forward<Params>(args)...);
  17.   if(cap<BS)
  18.     return std::string(buf, cap);
  19.   std::vector<char> out(cap+1);
  20.   std::snprintf(out.data(), cap+1, fmt, std::forward<Params>(args)...);
  21.   return std::string(out.data(), cap);
  22. }
  23.  
  24. int main()
  25. {
  26.   std::string x = pformat("Hill #%d, winner %s and %d", 1234, "Superman", 4321);
  27.   std::cout << "--->|" << x << "|<---" << std::endl;
  28.   std::cout << x.size() << std::endl;
  29.   std::string y = pformat("This will be surely a little bit longer than 100"
  30.     " characters which is the limit for another strategy in pformat():"
  31.     " Hill #%d, winner %s and %d", 1234, "Superman", 4321);
  32.   std::cout << "--->|" << y << "|<---" << std::endl;
  33.   std::cout << y.size() << std::endl;
  34.   return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement