-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpputil.cpp
More file actions
45 lines (37 loc) · 1.06 KB
/
cpputil.cpp
File metadata and controls
45 lines (37 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <cstdarg>
#include <cstdio>
#if __cplusplus < 201703L
# include <memory>
#endif
#include "cpputil.h"
// See: https://codereview.stackexchange.com/questions/187183/create-a-c-string-using-printf-style-formatting
std::string cpputil::format(const char *fmt, ...)
{
char buf[256];
va_list args;
va_start(args, fmt);
const auto r = std::vsnprintf(buf, sizeof buf, fmt, args);
va_end(args);
if (r < 0)
// conversion failed
return {};
const size_t len = r;
if (len < sizeof buf)
// we fit in the buffer
return { buf, len };
#if __cplusplus >= 201703L
// C++17: Create a string and write to its underlying array
std::string s(len, '\0');
va_start(args, fmt);
std::vsnprintf(s.data(), len+1, fmt, args);
va_end(args);
return s;
#else
// C++11 or C++14: We need to allocate scratch memory
auto vbuf = std::unique_ptr<char[]>(new char[len+1]);
va_start(args, fmt);
std::vsnprintf(vbuf.get(), len+1, fmt, args);
va_end(args);
return { vbuf.get(), len };
#endif
}