Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>C++11 solution that uses <code>vsnprintf()</code> internally:</p> <pre><code>#include &lt;stdarg.h&gt; // For va_start, etc. std::string string_format(const std::string fmt, ...) { int size = ((int)fmt.size()) * 2 + 50; // Use a rubric appropriate for your code std::string str; va_list ap; while (1) { // Maximum two passes on a POSIX system... str.resize(size); va_start(ap, fmt); int n = vsnprintf((char *)str.data(), size, fmt.c_str(), ap); va_end(ap); if (n &gt; -1 &amp;&amp; n &lt; size) { // Everything worked str.resize(n); return str; } if (n &gt; -1) // Needed size returned size = n + 1; // For null char else size *= 2; // Guess at a larger size (OS specific) } return str; } </code></pre> <p>A safer and more efficient (I tested it, and it is faster) approach:</p> <pre><code>#include &lt;stdarg.h&gt; // For va_start, etc. #include &lt;memory&gt; // For std::unique_ptr std::string string_format(const std::string fmt_str, ...) { int final_n, n = ((int)fmt_str.size()) * 2; /* Reserve two times as much as the length of the fmt_str */ std::unique_ptr&lt;char[]&gt; formatted; va_list ap; while(1) { formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */ strcpy(&amp;formatted[0], fmt_str.c_str()); va_start(ap, fmt_str); final_n = vsnprintf(&amp;formatted[0], n, fmt_str.c_str(), ap); va_end(ap); if (final_n &lt; 0 || final_n &gt;= n) n += abs(final_n - n + 1); else break; } return std::string(formatted.get()); } </code></pre> <p>The <code>fmt_str</code> is passed by value to conform with the requirements of <code>va_start</code>.</p> <p>NOTE: The "safer" and "faster" version doesn't work on some systems. Hence both are still listed. Also, "faster" depends entirely on the preallocation step being correct, otherwise the <code>strcpy</code> renders it slower.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload