Created
January 23, 2017 13:19
-
-
Save pyrtsa/08d5e168d3ee2ea44b98af1a8a1f3ccb to your computer and use it in GitHub Desktop.
Simple fprintf-style std::string formatting in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <cstdio> | |
#include <vector> | |
#include <iostream> | |
[[gnu::format(printf, 1, 2)]] | |
auto format(const char * fmt, ...) -> std::string { | |
va_list args1; | |
va_start(args1, fmt); | |
va_list args2; | |
va_copy(args2, args1); | |
std::vector<char> buf(1 + std::vsnprintf(nullptr, 0, fmt, args1)); | |
va_end(args1); | |
std::vsnprintf(buf.data(), buf.size(), fmt, args2); | |
va_end(args2); | |
return buf.data(); | |
} | |
int main() { | |
int i = 123; | |
// warning: format specifies type 'double' but the argument has type 'int' [-Wformat] | |
auto str = format("%f\n", i); | |
// ~~ ^ | |
// %d | |
std::cout << str; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment