Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // Required for main
- #include <string>
- #include <vector>
- #include <cstdio>
- /**
- * Creates a string from a printf format and the arguments by wrapping snprintf.
- * Uses on-stack buffer under 100 total length, allocates on heap otherwise.
- */
- template<typename ... Params>
- std::string pformat(char const *fmt, Params&& ... args)
- {
- const int BS = 100;
- char buf[BS];
- int cap = std::snprintf(buf, BS, fmt, std::forward<Params>(args)...);
- if(cap<BS)
- return std::string(buf, cap);
- std::vector<char> out(cap+1);
- std::snprintf(out.data(), cap+1, fmt, std::forward<Params>(args)...);
- return std::string(out.data(), cap);
- }
- int main()
- {
- std::string x = pformat("Hill #%d, winner %s and %d", 1234, "Superman", 4321);
- std::cout << "--->|" << x << "|<---" << std::endl;
- std::cout << x.size() << std::endl;
- std::string y = pformat("This will be surely a little bit longer than 100"
- " characters which is the limit for another strategy in pformat():"
- " Hill #%d, winner %s and %d", 1234, "Superman", 4321);
- std::cout << "--->|" << y << "|<---" << std::endl;
- std::cout << y.size() << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement