Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Blog
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
Please
log in
to post a comment.
VC++ windows exception
Dices by GOOSE
Workaround for https://github.com/Project-OSRM/osrm-backend/pull/4385
hangman
vc++ bug?
msvc set-terminate
dharm1
fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
Two-phase sample with VC++ 2015
zero size std::array parameter
Please log in to post a comment.