SatDump 2.0.0-alpha-76a915210
Loading...
Searching...
No Matches
format.h
Go to the documentation of this file.
1#pragma once
2
7
8#include <sstream>
9#include <vector>
10
11namespace satdump
12{
21 template <typename T>
22 std::string to_string_with_precision(const T a_value, const int n = 6)
23 {
24 std::ostringstream out;
25 out.precision(n);
26 out << std::fixed << a_value;
27 return out.str();
28 }
29
38 template <typename... T>
39 std::string svformat(const char *fmt, T &&...args)
40 {
41 // Allocate a buffer on the stack that's big enough for us almost
42 // all the time.
43 size_t size = 1024;
44 std::vector<char> buf;
45 buf.resize(size);
46
47 // Try to vsnprintf into our buffer.
48 size_t needed = snprintf((char *)&buf[0], size, fmt, args...);
49 // NB. On Windows, vsnprintf returns -1 if the string didn't fit the
50 // buffer. On Linux & OSX, it returns the length it would have needed.
51
52 if (needed <= size)
53 {
54 // It fit fine the first time, we're done.
55 return std::string(&buf[0]);
56 }
57 else
58 {
59 // vsnprintf reported that it wanted to write more characters
60 // than we allotted. So do a malloc of the right size and try again.
61 // This doesn't happen very often if we chose our initial size
62 // well.
63 size = needed;
64 buf.resize(size);
65 needed = snprintf((char *)&buf[0], size, fmt, args...);
66 return std::string(&buf[0]);
67 }
68 }
69} // namespace satdump
std::string svformat(const char *fmt, T &&...args)
Format a std::string with a standard printf formatting pattern.
Definition format.h:39
std::string to_string_with_precision(const T a_value, const int n=6)
Format a number to string with a specific float precision.
Definition format.h:22