Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
C++ string format
#include <string> #include <cstdarg> #include <memory> std::string format(const char* format, ...) { va_list args; va_start(args, format); #ifndef _MSC_VER size_t size = std::snprintf( nullptr, 0, format, args) + 1; // Extra space for '\0' std::unique_ptr<char[]> buf( new char[ size ] ); std::vsnprintf( buf.get(), size, format, args); return std::string(buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside #else int size = _vscprintf(format, args); std::string result(++size, 0); vsnprintf_s((char*)result.data(), size, _TRUNCATE, format, args); return result; #endif va_end(args); } int main() { float f = 3.f; int i = 5; std::string s = "hello!"; auto rs = format("i=%d, f=%f, s=%s", i, f, s.c_str()); printf("%s", rs.c_str()); return 0; }
run
|
edit
|
history
|
help
0
0004
Triangle N5
calling conventions and using an override class to change another classes values
hangman
Dynamically sized array at end of struct
jkljklj
C++ move/copy constructor and assignment demo
Multi Inheritance
Adaptive return type
MSVC14 <exception> header