Thrill  0.1
ssprintf.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/ssprintf.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2007-2019 Timo Bingmann <[email protected]>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
11 #include <tlx/string/ssprintf.hpp>
12 
13 #include <cstdarg>
14 #include <cstdio>
15 
16 namespace tlx {
17 
18 std::string ssprintf(const char* fmt, ...) {
19  std::string out;
20  out.resize(128);
21 
22  va_list args;
23  va_start(args, fmt);
24 
25  int size = std::vsnprintf(
26  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
27 
28  if (size >= static_cast<int>(out.size())) {
29  // error, grow buffer and try again.
30  out.resize(size);
31  size = std::vsnprintf(
32  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
33  }
34 
35  out.resize(size);
36 
37  va_end(args);
38 
39  return out;
40 }
41 
42 std::string ssnprintf(size_t max_size, const char* fmt, ...) {
43  std::string out;
44  out.resize(max_size);
45 
46  va_list args;
47  va_start(args, fmt);
48 
49  int size = std::vsnprintf(
50  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
51 
52  if (static_cast<size_t>(size) < max_size)
53  out.resize(static_cast<size_t>(size));
54 
55  va_end(args);
56 
57  return out;
58 }
59 
60 } // namespace tlx
61 
62 /******************************************************************************/
std::string ssprintf(const char *fmt,...)
Helper for return the result of a sprintf() call inside a std::string.
Definition: ssprintf.cpp:18
std::basic_string< char, std::char_traits< char >, Allocator< char > > string
string with Manager tracking
Definition: allocator.hpp:220
std::string ssnprintf(size_t max_size, const char *fmt,...)
Helper for return the result of a snprintf() call inside a std::string.
Definition: ssprintf.cpp:42