Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Easy enough with <code>std::string</code>:</p> <pre><code>std::string foo = "C++"; auto bar = "this is a " + foo + " example."; </code></pre> <p>Just make sure one of the first two operands is a <code>std::string</code>, not both <code>const char *</code> or something.</p> <hr> <p>As noted below, this result is being used in <code>CreateProcess</code> as a <code>char *</code> (<code>LPSTR</code>) argument. If the argument was <code>const char *</code>, <code>c_str()</code> would be perfectly acceptable to pass in. However, it is not, which means you should assume it modifies the string. MSDN says this:</p> <blockquote> <p>The Unicode version of this function, CreateProcessW, can modify the contents of this string.</p> </blockquote> <p>Since this is <code>char *</code>, it's evidently using <code>CreateProcessA</code>, so I'd say a <code>const_cast&lt;char *&gt;</code> <em>should</em> work, but it's better to be safe.</p> <p>You have two main options, one for C++11 and later, and one for pre-C++11.</p> <h3>C++11</h3> <p><code>std::string</code>'s internal buffer is now guaranteed to be contiguous. It's also guaranteed to be null-terminated. That means you can pass a pointer to the first element:</p> <pre><code>CreateProcess(..., &amp;str[0], ...); </code></pre> <p>Make sure the function only overwrites indices within [0, size()) in the internal array. Overwriting the guaranteed null-terminator is not good.</p> <h3>C++03</h3> <p><code>std::string</code> is not guaranteed to be contiguous or null-terminated. I find it best to make a temporary <code>std::vector</code>, which guarantees the contiguous part, and pass a pointer to its buffer:</p> <pre><code>std::vector&lt;char&gt; strTemp(str.begin(), str.end()); strTemp.push_back('\0'); CreateProcess(..., &amp;strTemp[0], ...); </code></pre> <p>Also note MSDN again:</p> <blockquote> <p>The system adds a terminating null character to the command-line string to separate the file name from the arguments. This divides the original string into two strings for internal processing.</p> </blockquote> <p>That seems to suggest that the null-terminator here isn't necessary, but there's no size parameter, so I'm not completely sure.</p>
 

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