Re:Accidentally Overwriting Another Local Variable in C and C++
by DerekL on Thursday December 05, 2019 @08:15PM
(#21718472)
C++20 is adding a type-safe alternative to printf, called std::format, though it doesn't provide warnings at compile time.
[ Parent
| on HN ]
Re:Accidentally Overwriting Another Local Variable in C and C++
by excessive on Thursday December 05, 2019 @10:03PM
(#21718926)
Here's one you can use with (pretty much) any version of C++:
__attribute__ ((format (printf, 1, 2)))
static inline std::string format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
size_t bytes = vsnprintf(0, 0, fmt, args);
va_end(args);
va_list again;
va_start(again, fmt);
std::string result(bytes, '\0');
vsnprintf(&result[0], bytes + 1, fmt, again);
va_end(again);
return result;
}
Re:Accidentally Overwriting Another Local Variable in C and C++
by Ididntdothis on Thursday December 05, 2019 @09:40PM
(#21718820)
They should have gone step further and done string interpolation how C# and JS can do. Really nice to use and avoids errors.